【发布时间】:2017-02-12 17:41:37
【问题描述】:
我刚刚遇到了一段对我来说似乎很奇怪的代码 sn-p(请参见下面的最小示例),derived::base 是对 base 类型的另一个对象的引用,有人可以帮我回答cmets中的问题?
class base{
public:
int a;
int b;
};
class derived : public base{
public:
double c;
void run(const base & bs){
((base &) *this) = bs; // what does this line do?
// Is derived::base now a copy of bs?
// If yes, but why not write ((base) *this) = bs?
// if not, then derived::base is a reference to bs,
// then does it mean the memory of derived::base
// and members of derived are no longer contiguous?
std::cout << "a = " << a << std::endl;
}
};
附言
@LightnessRacesinOrbit 的 cmets 帮助解决了很多问题,但我只能接受一个答案帖子,最好是 @WhiZTiM
【问题讨论】:
-
它所做的只是调用基类的复制构造函数,它将复制基类的成员(即
a和b)而不触及对象派生部分中的任何内容(即c)。我不明白为什么内存不再连续。 -
afaik 你永远无法保证对象成员存储在连续内存中,即使没有这种“仅复制基类成员”技巧。也许对“连续”的含义有些误解。您能否详细解释一下您对该代码的担忧之处?
-
@imreal,但如果调用复制构造函数,为什么不写
((base) *this) = bs? -
@tobi303,我担心的是,如果只是调用复制构造函数,为什么不直接写
((base) *this) = bs或derived::base = bs呢?
标签: c++