2010-09-21 91 views
3

我有代码如下:C++虚拟inheritace和类型转换/拷贝构造混乱

class A 
{ 
}; 

class B: public virtual A 
{ 
public: 
    B() 
    { 
     cerr << "B()"; 
    } 
    B(const A& a) 
    { 
     cerr << "B(const A&)"; 
    } 
}; 

class C: public B 
{ 

}; 

int main(int argc, char **argv) 
{ 
    B *b = new B(C()); 
} 

令我惊讶B(const的甲&一个)不被调用。这是为什么?

+0

这与使用虚拟继承的事实没有任何关系;非虚拟继承会表现出相同的行为。 – 2010-09-21 15:23:09

回答

8

B还具有以下

B(const B&); 

这隐式声明的成员函数被调用,因为它是C类型的参数比你的用户声明的构造更好的匹配所声明的隐式声明的拷贝构造函数,B(const A&)

1

这就是我,当我在你的代码

class B : virtual public A { 
    class B; 
public: 
    B() : A() (CompoundStmt 0xb85950 <a.cpp:9:5, line:11:5>) 


    B(A const &a) : A() (CompoundStmt 0xb859c0 <a.cpp:13:5, line:15:5>) 


    inline B &operator=(B const &) throw(); 
    inline void ~B() throw(); 
    inline B(B const &) throw() : A((ImplicitCastExpr 0xb86a10 <a.cpp:5:7> 'clas 
s A const' <UncheckedDerivedToBase (virtual A)> lvalue 
    (DeclRefExpr 0xb869ec <col:7> 'class B const' ParmVar='' 0xb86170)) 
) (CompoundStmt 0xb86ab0 <a.cpp:5:7>) 

试图clang++ -cc1 -ast-dump正如你可以看到你的B类有一个隐式声明(编译器合成的)复制构造函数。

inline B(B const &) throw():这是C类型的更好匹配,James McNellis表示his answer。这就是为什么你没有看到B(const A& a)的呼叫,因为它从来没有被实际调用。