如果想让你的类不能使用copy构造函数和赋值操作符,只要将该类的copy构造函数和赋值操作符函数定义为private即可,并且只是声明,不用实现.
- class TestClass
- {
- public:
- TestClass()
- :X(0)
- {
- }
- TestClass(int x)
- :X(x)
- {
- }
- ~TestClass(){}
- void Show()
- {
- cout << "X = " << X << endl;
- }
- private:
- TestClass(const TestClass&);
- TestClass& operator=(const TestClass&);
- private:
- int X;
- };
- int main()
- {
- TestClass t(3);
- t.Show();
- TestClass t1(t);
- TestClass t2;
- t2 = t;
- return 0;
- }
编译错误为:
'TestClass::TestClass' : cannot access private member declared in class 'TestClass'
'TestClass::operator =' : cannot access private member declared in class 'TestClass'
这种方法的一点小缺陷是,如果该类的成员函数或其friend函数调用copy构造函数或赋值操作符函数,会将错误推后到连接期。有一种方法可以将连接期错误移至编译期。
先定义一个基类
- class UnCopyable
- {
- public:
- UnCopyable();
- ~UnCopyable();
- private:
- UnCopyable(const UnCopyable&);
- UnCopyable& operator=(const UnCopyable&);
- };
然后让你的类继承UnCopyable类
- class TestClass : public UnCopyable
- {
- public:
- TestClass()
- :X(0)
- ,Y(0)
- {
- }
- TestClass(int x, int y)
- :X(x)
- ,Y(y)
- {
- }
- ~TestClass(){}
- void Show()
- {
- cout << "X = " << X << ", Y = " << Y << endl;
- }
- private:
- int X;
- int Y;
- };
其继承方式,不一定为 public,亦可为private
阅读(4138) | 评论(0) | 转发(0) |