【编程语法-C++】课堂总结17-20

引用

引用不会创建新的变量,会修改原始值。

int a = 5;
int& ref = a;
ref = 2;
std::cout<<a<<std::endl; // a会变成2

def Increase1(int a){
    a++;
}
def Increase2(int& a){
    a++;
}
Increase1(a)
std::cout<<a<<std::endl; // a还是2,因为这个函数并没有改变外部的值
Increase2(a)
std::cout<<a<<std::endl; // a变成3,因为引用可以实际改变该内存位置上的值

指针重新指向时,需要先解引用

a = 4;
b = 4;
int* ptr = &a;
*ptr = 2; // 解引用
ptr = &b;
*ptr = 1;
// a=2, b=1

class Player
{
public:
    int x, y;
    int speed;

    void move(int xa, int ya)
    {
        x += xa * speed;
        y += ya * speed;
    }
}

Player p1; //实例化
p1.x = 0; //这儿能执行的前提是成员变量的访问属性已经变成公有的
p1.move(-1,1);

struct和class区别

实际上区别很小,只有一个区别,class的属性默认是私有的,而struct默认是共有的,不用人为再加修饰符。

c++保留struct的原因是因为维持和c的兼容性,因为c中没有类,但c有struct结构体,所以如果我们删除struct就会失去所有兼容性。因为c++的编译器此时就不知道struct是什么。当然此时可以使用“#define struct class”来修复。

一般在实际编程过程中,有以下几点不同(但从技术层面上是没什么区别的):

  • struct我们一般只作为一系列简单变量的操作,而class在此基础上会有更加丰富的属性和功能。
  • 一般struct不会用于继承。

创建一个基础的打印类

class Log
{
public:
    const int LogLevelError = 0;
    const int LogLevelWarning = 1;
    const int LogLevelInfo = 2;

private:
    int loglevel = LogLevelInfo;

public:
    void SetLevel(int level)
    {
        loglevel = level;
    }

    void Error(const char* message)
    {
        if (loglevel>=LogLevelError)
            std::cout << "[ERRO]: " << message << std::endl;
    }

    void Warn(const char* message)
    {
        if (loglevel>=LogLevelWarning)
            std::cout << "[WARN]: " << message << std::endl;
    }

    void Info(const char* message)
    {
        if (loglevel>=LogLevelInfo)
            std::cout << "[INFO]: " << message << std::endl;
    }
}; //记得加分号
全部评论

相关推荐

ResourceUtilization:我嘞个董事长
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务