通过派生类构造函数初始化后,从main()访问基类变量
accessing base class variable from main() after initializing through derived class constructor
考虑以下代码,其中基类构造函数是通过派生类构造函数初始化的。当我试图从main
访问基类值x
时,它会返回0而不是5。我的理解有什么问题?
#include <iostream>
using namespace std;
class Base
{
public:
int x;
Base() {}
Base(int a)
{
x = a;
}
};
class Der:public Base
{
public:
Der(int y) : Base(y)
{
x = y;
}
};
int main()
{
Base *ob1 = new Base();
Der *ob = new Der(5);
cout << ob1->x;
return 0;
}
当您调用new Base()
时,您会从默认构造函数中获得一个对象。恰好根本没有初始化x
,因此您的代码具有未定义的行为。这次你碰巧看到0
,但这并不能保证。
调用new Der(5)
时,会得到一个不同的对象,该对象使用int
构造函数。在您的情况下,在Der(int)
中设置x = y
是不必要的,因为您已经调用了Base(y)
。以下行应输出5
:
cout << ob->x;
还要注意,在本例中没有使用动态分配的理由。完全可以使用堆栈:
int main()
{
Base base;
Der derived(5);
cout << "Base (undefined behaviour): " << base.x << endl;
cout << "Derived (defined): " << derived.x << endl;
return 0;
}
相关文章:
- 函数是否可以访问传递给main()的参数
- 有没有办法通过 main 函数访问受保护的矢量大小而无需将其转换为公共?
- 访问除main.cpp之外的.cpp文件中的QMLEngine/rootObject属性
- 在 main() 中访问类成员时C++分段错误
- main() 对连续运行的线程中的编辑值具有只读访问权限 - C++
- WriteConsole访问在功能调用中违反,而不是来自main()
- 是否可以从创建其创建的Main()之外的公共类成员访问公共类成员
- 将静态库转换为 DLL 会导致在 main 之前出现访问冲突
- 进入MAIN之前,访问违规位置
- main()::__lambda1 不是 std::_Tuple_impl<1ul, main()::__lambda1> 的可访问基础
- 如何使用 x86 程序集在 c 中访问 main 函数中的变量
- 从C (例如Main.CPP)访问注册类型实例
- C++ 如何从 main() 外部访问在 main() 中初始化的对象
- c++抛出0xC0000005:写入位置0xFEEEFEEE的访问冲突.从main返回时
- 通过派生类构造函数初始化后,从main()访问基类变量
- main.cpp 无法访问头文件和其他.cpp文件中的变量和函数
- 从main中的类访问数组
- main.exe 中0x779615de处未处理的异常:0xC0000005:访问违规写入位置0x003f0014
- 我无法使用指针数组从main访问函数(在类中)
- 从main访问类的受保护成员