我刚刚遇到一段代码片段,对我来说似乎很奇怪(请参阅下面的最小示例),derived::base
是对base
类型的另一个对象的引用,有人可以帮助我回答评论中的问题?
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;
}
};
PS
答案 0 :(得分:2)
void run(const base & bs){
((base &) *this) = bs;
std::cout << "a = " << a << std::endl;
}
以上代码可以细分为:
void run(const base & bs){
base& base_of_this_instance = *this;
base_of_this_instance = bs;
std::cout << "a = " << a << std::endl;
}
derived
对象的内存可以表示为:
|| int a |x| int b |y| int c || // <- x and y represents some hypothetical padding
|| base |y| || // <- We can slice `derived` and retrieve only base
|| derived || // <- Memory consumed by derived
在derived::run
方法中,首先,获得对base
derived
部分的引用,其次base
被分配给bs
。此赋值将调用base
的复制赋值运算符。这意味着基础部分现在将保留bs
中的任何内容的副本。
答案 1 :(得分:0)
的结果
((base &) *this)
是对基类的引用
您可以将其保存为变量:
base& refToBase = ((base &) *this);
refToBase是对同一个对象的引用,即
之后你有作业
refToBase = bs;
它会将bs的值赋给refToBase对象
像这样:
int i = 10;
int p = 20;
int& refI = i;
int& refP = p;
refI = refP; // i == 20
p = 15; // p ==15 but i == 20
所以在你的例子中的“奇怪代码”被执行后,我们在derived :: a和derived :: b
中有bs.a和bs.b的副本derived :: base和derived :: c的内存仍然是一个批处理