gpt4 book ai didi

c++ - 基类是对另一个对象的引用

转载 作者:行者123 更新时间:2023-11-30 03:34:16 26 4
gpt4 key购买 nike

我刚刚遇到了一段对我来说很奇怪的代码(见下面的一个最小示例),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;

}
};

附言

@LightnessRacesinOrbit 的评论对解决问题有很大帮助,但我只能接受一个答案帖子,最好的是@WhiZTiM

最佳答案

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 方法中,首先,获取对derivedbase 部分的引用,其次是 base 被分配给 bs。此赋值将调用 base 的复制赋值运算符。这意味着基础部分现在将保存 bs 中的任何内容的拷贝。

关于c++ - 基类是对另一个对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42190966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com