我的代码中有一个案例,我想使用对象切片,但我正在尝试确定这样做是否安全或聪明。为了确定这一点,我运行了以下示例:
#include <iostream>
using namespace std;
class Dog{
public:
Dog( int x )
:x{x}
{
};
int x;
};
class Spaniel: public Dog{
public:
Spaniel( int x, int y )
:Dog{x}, y{y}
{
}
int y;
};
class Green{
public:
Green( int q )
:q{q}
{
}
int q;
};
class GreenSpaniel: public Spaniel, public Green{
public:
GreenSpaniel( int x, int y, int q, int z )
:Spaniel{x,y}, Green{q}, z{z}
{
}
int z;
};
int main(){
GreenSpaniel jerry{ 1,2,3,4 };
Green fred = jerry;
cout << fred.q << endl; //correctly displays "3"
return 0;
}
我期待它返回 1,因为基类不是最顶层(根),但它显示 3。所以,我的问题是它为什么/如何显示正确答案,这是一种安全的做法吗?如果任何一个类有虚拟表,你的答案会有什么变化?如果您认为它不安全,您是否有任何解决方法可以从派生对象复制非根基础对象?
我使用以下命令在 gcc 4.6.3 下的 linux 中运行它:
g++ -std=c++0x main.cc