C++中老生常谈的基础是构造函数,申明一个空的class Empty,其实编译器会自动产生默认构造函数、析构构造函数、复制构造函数、赋值构造函数如下代码所示:
class Empty{};
定义上面的类,其实可以编译器会产生如下结构
class Empty {
public:
Empty() ; //默认构造函数
~Empty() ;//析构构造函数
Empty(const Empty& emp) ; //复制构造函数
Empty& operator=(const Empty& emp); //赋值构造函数
};
Notice1:
copy construct 函数以及copy-assignment construct函数背后隐藏的是对于non-static成员的复制
Notice2:
面对reference 类型和const类型的成员变量,默认copy-assignment construct函数是没法直接进行操作的,必须用户自定义类的copy-assignment construct
示例代码如下:
#include <iostream>
#include <string>
template<class T>
class NameObject {
public:
NameObject(std::string r_name, const T& r_value) :
name(r_name),
value(r_value) {}
NameObject(const NameObject& new_obj) {
name = new_obj.name;
value = new_obj.value;
}
NameObject& operator=(const NameObject& new_obj) {
if (&new_obj == this) {
return *this;
}
return *(new NameObject(new_obj.name, new_obj.value));
}
void print() {
std::cout << name << std::endl;
std::cout << value << std::endl;
}
private:
std::string& name;
const T value;
};
int main() {
std::string str1 = "tangye";
std::string str2 = "liuxinwang";
NameObject<int> p(str1, 3);
NameObject<int> s(str2, 28);
s.print();
p.print();
p = s; // 需要自行定义拷贝构造函数,不然编译器会报错
p.print();
}
Notice3:
若不想调用编译器自带的拷贝构造函数或者是赋值构造函数,就应该明确拒绝;拒绝的方式是——继承base_class,base_class中声明copy construct 和copy assignment construct为private成员;
class Uncopy {
public:
Uncopy() {}
~Uncopy() {}
private:
Uncopy(const Uncopy& copy);
Uncopy& operator=(const Uncopy& copy);
};
class Child :: private Uncopy {
};
引发的疑问点:为什么不直接在类Child中声明copy construct 和copy assignment construct为private成员???为了避免Child类的friend 或 member可以继续调用拷贝构造函数和赋值构造函数。