【发布时间】:2013-06-21 07:33:37
【问题描述】:
考虑以下场景: 一些多态类:
struct iClass
{
virtual ~iClass(){}
};
struct CommonClass : public iClass
{
char str[128];
CommonClass() { ... }
...
};
struct SpecificClass : public iClass
{
char str[32];
SpecificClass () { ... }
SpecificClass (SpecificClass& src) { strcpy(...); ... }
SpecificClass (CommonClass& src) { strcpy(...); ... }
SpecificClass (const CommonClass& src) { strcpy(...); ... }
void foo() { ... }
};
还有一个函数:
void someFunc(SpecificClass sc) { sc.foo(); } // pass by value: i want it copied!
int main ()
{
CommonClass comCl;
someFunc(comCl); // <- Error: no matching function for call to 'SpecificClass::SpecificClass(SpecificClass)' NOTE: no &
SpecificClass specCl(comCl);
someFunc(specCl); // Works normal, but the str gets copied double times this way, isnt it?
return 0;
}
为什么编译器不允许在第一个函数调用中从 CommonClass 转换为 SpecificClass,尽管无论如何都会在调用中构造一个新的 SpecificClass 并且有一个用于此特定转换的构造函数? 为什么我会收到这个奇怪的错误信息?在没有引用的情况下调用复制构造函数? 谁能分享一些对此问题的见解?
顺便说一句,我必须使用 gcc 4.1.2
【问题讨论】:
-
您的构造函数采用
CommonClass &,但您需要一个接受const CommonClass &的构造函数。就目前而言,您正在尝试将右值绑定到非 const 左值引用。 -
你的意思是什么部分是右值?我在这里没有看到任何常量?
-
好吧,我在 commonClass 的 specificClass 中添加了一个 const 构造函数。还是同样的错误!但现在又多了一个“候选人”;)
-
是的,在普通的复制构造函数中也需要使用
const SpecificClass &。
标签: c++ gcc constructor polymorphism implicit-conversion