本文介绍了C ++:可以多态复制构造函数工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑:
class A
{
public:
A( int val ) : m_ValA( val ) {}
A( const A& rhs ) {}
int m_ValA;
};
class B : public A
{
public:
B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {}
B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {}
int m_ValB;
};
int main()
{
A* b1 = new B( 1, 2 );
A* b2 = new A( *b1 ); // ERROR...but what if it could work?
return 0;
}
如果new A( b1)能够解析为创建新的B副本并返回A
Would C++ be broken if "new A( b1 )" was able to resolve to creating a new B copy and returning an A?
这会有用吗?
推荐答案
你需要这个功能,还是只是一个思想实验?
Do you need this functionality, or is this just a thought experiment?
如果你需要这样做,常见的成语是有一个 Clone
方法:
If you need to do this, the common idiom is to have a Clone
method:
class A
{
public:
A( int val ) : m_ValA( val ) {}
A( const A& rhs ) {}
virtual A *Clone () = 0;
int m_ValA;
};
class B : public A
{
public:
B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {}
B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {}
A *Clone() { return new B(*this); }
int m_ValB;
};
int main()
{
A* b1 = new B( 1, 2 );
A* b2 = b1->Clone();
return 0;
}
这篇关于C ++:可以多态复制构造函数工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!