拷贝构造
C++的拷贝构造有点类似于C的结构体拷贝,根据现有的对象拷贝给另一个对象.
一般来说C++编译器会自动给类生成拷贝构造函数(前提是调用的代码中有拷贝构造的行为),
但如果类已经定义了拷贝构造函数 则编译器不会再去生成.
利用这个特点:
代码中如果不希望某个类被拷贝构造,则可以通过重载拷贝构造函数,
并声明为private属性来实现.
示例代码
1 #include <iostream>
2 class test {
3 public:
4 test(int nb) : cnt(nb) {}
5 int cnt;
6 private:
7 test(const test &);
8 test &operator=(const test &);
9 };
10
11 int main(int argc, char **argv) {
12 int ret = 0;
13
14 test a(5);
15 std::cout << "a:" << a.cnt << std::endl;
16 test b(a);
17 std::cout << "b:" << b.cnt << std::endl;
18
19 return 0;
20 }