|
我正在尝试使用基类和派生类来理解悬空指针。
#include <iostream>
// Base class
class BaseClass
{
private:
protected:
int size; // Size of the array
public:
int *data; // Private array field
BaseClass(int size) : size(size)
{
data = new int[size];
std::cout << "BaseClass constructor" << std::endl;
}
// Destructor for BaseClass
~BaseClass()
{
delete[] data;
std::cout << "BaseClass destructor" << std::endl;
}
// Function to print array elements
void printData() const
{
for (int i = 0; i < size; ++i)
{
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
};
// Derived class
class DerivedClass : public BaseClass
{
public:
// Constructor for DerivedClass
DerivedClass(int size) : BaseClass(size)
{
for (int i = 0; i < size; ++i)
{
data[i] = i + 1;
}
std::cout << "DerivedClass constructor" << std::endl;
}
~DerivedClass()
{
std::cout << "DerivedClass destructor" << std::endl;
}
};
int main()
{
// Create an object of the derived class
BaseClass *base = nullptr;
if (true)
{
DerivedClass derivedObject(5);
base = &derivedObject;
}
if (base)
{
base->printData();
}
else
{
std::cout << "Derived is null" << std::endl;
}
return 0;
}
在 cpp.sh 上编辑和运行
程序的输出是
BaseClass 构造函数 DerivedClass 构造函数
DerivedClass 析构函数 BaseClass 析构函数
1 2 3 4 5
我不明白的是,DerivedClass 应该超出范围,正如被调用的析构
函数所指出的那样。我认为基本指针现在应该什么都不指向。
我只是不确定为什么输出不是“派生为空”
,我在 Windows 上使用 vscode 和 MinGW 作为编译器。
|
|