创建子类对象时, 是为超类创建的第二个对象
When a subclass object is created, is a second object created for the Superclass?
当一个实例变量被继承时,在子类中更改它不会影响它在超类中的值,反之亦然。这意味着有两个实例变量。但是当我做sizeof( sublcass )
时,大小中只考虑了一个实例变量。那么有没有为超类创建的第二个对象?
这里有一个小片段来说明我在说什么:
struct Super {
int x;
void func() {
cout << "SUPERCLASS" << endl;
cout << x << endl; /* prints garbage value */
x = 4;
cout << x << endl; /* prints 4 */
}
};
struct Sub : public Super {
void func() {
x = 10;
Super b;
b.func();
cout << "SUB" << endl;
cout << x << endl; /* prints 10 */
}
};
int main() {
Sub b;
b.func();
return 0;
}
输出:
SIZE: 4
SUPERCLASS
2867344
4
SUB
10
在此函数中,创建一个类型为 Super
的新对象并打印它。
void func() {
x = 10;
// b is now a totally different (and unrelated object)
// so calling b.func() will print the x variable that
// is valid for that instance (not this instance)
Super b;
b.func();
cout << "SUB" << endl;
cout << x << endl; /* prints 10 */
}
您的假设实际上是不正确的,只有一个实例变量x
存在于您的类Sub
中。 你的函数Sub::func()
有隐藏Super::func()
,为了调用它,你需要使用范围解析运算符(::
)直接调用它。
void func() {
// this is the one (and only) x that is in scope
// inherited by `Sub` from `Super`.
x = 10;
// call Super::func(), using the scope resolution operator
Super::func();
cout << "SUB" << endl;
cout << x << endl; /* prints 10 */
}
如果您只是明确使用数据成员,您应该看到问题所在:
void func() {
this->x = 10;
Super b;
b.func();
cout << "SUB" << endl;
cout << this->x << endl; /* prints 10 */
}
由于this
显然不等于&b
因此您应该清楚地看到您正在访问不同对象的成员。
相关文章:
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何创建对象函数指针C++映射?
- C++创建对象数组
- 在 C++ 的 Switch Case 中创建对象后对对象调用方法
- 如何获取在 main() 函数中构造的类的创建对象?
- 基于文件中的条目创建对象
- 错误:创建对象后无法分配区域
- C++ 通过输入创建对象
- 堆还是堆栈用于创建对象?
- 使用 C++ 创建对象数组
- 使用unique_ptr创建对象
- C++递归地在类构造函数中创建对象
- 通过向构造函数其他对象引用页面来创建对象
- ReactiveX (rx) - 在对象上应用可观察对象,而不是在可观察对象中创建对象
- 如何在OSX上正确创建C++对象文件(.o)
- 编译器是否会创建vtable,而不考虑在c++中创建对象
- 创建对象并防止被破坏
- 在C++中,友元类可以从友元类创建对象吗
- 只在堆中创建C++对象
- 创建用户定义的复制构造函数时无法创建对象