导读章

01. explicit关键字

通常会将一个构造函数声明为explicit,可以防止被隐式转换。

class B {
public:
    explicit B(int x=0);
};
void DoSomething(B objB);

// 此时若没有explicit,那么
DoSomething(3); // 是可以运行的
// 有explicit,那么便不可以了,只能写成
DoSomething(B(3)); // 这个样子

02. copy 方法

有两种

class B {
public:
    B();
    B(const B&);
    B& operator=(const B&);
};

如果声明了新的对象,那么一定会调用一个构造函数:

B b1; // 调用默认构造函数
B b2 = b1; // 调用copy构造函数

而如果只是单纯的赋值,才会调用=函数:

B b1, b2; // 都会调用默认构造函数
b2 = b1; // 此时会调用赋值函数

results matching ""

    No results matching ""