【发布时间】:2014-10-28 15:44:12
【问题描述】:
我想了解在显式复制构造函数中应该使用哪些正确的参数类型。
如下定义,使用“显式”,赋值代码将无法编译。 main 中的赋值行生成错误:'没有匹配的构造函数用于初始化 CCat'
从第一个复制构造函数中删除“显式”可以解决问题,但我不明白为什么。
编译器显然在做一些微妙的隐式转换?
class CCat : public CAnimal
{
public:
explicit CCat( string name, uint noLegs, bool fur, bool domestic, string breed );
explicit CCat( const CCat& oldCat ) : CAnimal( oldCat )
{
std::cout << "\nCCat::CCat( const CCat& oldCat ) \n";
}
explicit CCat( CCat& oldCat ) : CAnimal( oldCat )
{
std::cout << "\nexplicit CCat::CCat( CCat& oldCat ) \n";
}
~CCat();
CCat& operator =( CCat oldCat ){
//.. do assignment stuff
return *this;
}
};
int main(int argc, const char * argv[])
{
CCat *cat1 = new CCat( string("Wiggy"), 4, true, true, string("Tabby") );
CCat *cat2 = new CCat( string("Tibles"), 4, true, true, string("Tom") );
CCat tempCat( *cat1 );
CCat tempCat2( *cat2 );
std::cout << "CCat tempCat2( *cat2 );\n";
const CCat& tempCat3 = *cat2;
tempCat = tempCat3; // will not compile without explicit removed from first C/Constr
tempCat = CCat(*cat2); // will not compile without explicit removed from first C/Constr
tempCat = tempCat2; // will not compile without explicit removed from first C/Constr
return 0;
}
赋值运算符(按值传递)强制使用复制构造函数,但是使用显式时无法找到完美匹配。那么当显式被移除时,编译器会执行哪些转换,我该如何编写匹配的复制构造函数?
【问题讨论】:
-
我不太明白你在问什么,你似乎已经发现了问题......
-
复制构造函数不应该是显式的。
-
您的赋值运算符是否在进行复制和交换或类似操作?否则它将采用 const 引用。
-
@T.C.为什么 Copy 构造函数不应该是显式的,什么是合理的?
标签: c++ copy-constructor assignment-operator