64,685
社区成员
发帖
与我相关
我的任务
分享
class NonCopyable
{
private:
NonCopyable(const NonCopyable&); // no implementation
NonCopyable& operator=(const NonCopyable&); // no implementation
public:
NonCopyable() { }
};
class DD:private NonCopyable
{
private:
int a;
public:
DD(){a=0;}
DD(int xx):a(xx){};
DD(const DD& xx){a=xx.a;}
DD& operator=(const DD& xx){a=xx.a;}
virtual ~DD(){};
void getA(){cout <<"a:"<< a << endl;};
};
DD xx,yy(1);
NonCopyable cc;
xx.getA();
xx=yy;
xx.getA();
cc=xx;//不行
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base()" << endl;
}
Base(const Base &)
{
cout << "Base(const Base &)" << endl;
}
Base & operator = (const Base &)
{
cout << "Base & operator = (const Base &)" << endl;
return (*this);
}
};
class Derive : private Base
{
public:
Derive()
{
cout << "Derive()" << endl;
}
Derive(const Derive &)
{
cout << "Derive(const Derive &)" << endl;
}
Derive & operator = (const Derive &)
{
cout << "Derive & operator = (const Derive &)" << endl;
return (*this);
}
};
int main() {
Derive d1;
Derive d2(d1);
Derive d3;
d3 = d1;
return 0;
}
如果我们想让DD(别的类也是一样)不能被拷贝, 一般会这么写:
class DD
{
// ...
private:
DD(const DD &);
DD & operator = (const DD &);
}
但这样写很麻烦, 因为我们得在每个有这种要求的类中都要写:
private:
XX(const XX &);
XX & operator = (const XX &);
所以就想到写个基类NonCopyable来做这个事, 这样我们就可以简写成:
class DD : public NonCopyable /* public("是一种"的关系, 而不是"有一个"的关系) */
{
// ...
/* 下面的不需要了 *
/*
private:
DD(const DD &);
DD & operator = (const DD &);
*/
}
但, LZ却又实现并提供(public)了子类的拷贝接口, 它当然可以拷贝了
LZ弄错前因后果了 ^_^