gpt4 book ai didi

c++ - 尝试学习指针时练习程序崩溃

转载 作者:行者123 更新时间:2023-11-30 03:41:15 24 4
gpt4 key购买 nike

我仍在掌握指针的过程中,为此我编写了一个快速但毫无意义的程序来练习查找指针错误。我对为什么这个示例代码崩溃感到困惑:

#include <iostream>

class VehiclePart
{
public:
VehiclePart(int);

int GetVehiclePartNumber();
private:
int partNumber;
};

VehiclePart::VehiclePart(int VehiclePartNumber)
{
partNumber = VehiclePartNumber;
}

int VehiclePart::GetVehiclePartNumber()
{
return partNumber;
}

class Vehicle
{
public:
Vehicle(VehiclePart* VehiclePart, int VehiclePartNumber);

int GetVehiclePartNumber();

private:
VehiclePart* vehiclePart;

};

Vehicle::Vehicle(VehiclePart* vehiclePart, int VehiclePartNumber)
{
vehiclePart = new VehiclePart(VehiclePartNumber);
}

int Vehicle::GetVehiclePartNumber()
{
return vehiclePart->GetVehiclePartNumber();
}

int main()
{
VehiclePart* hood = nullptr;
Vehicle car(hood, 6);

std::cout << "Hello" << std::endl;

std::cout << car.GetVehiclePartNumber();

return 0;
}

我知道有更好的方法来处理事情,就像我说的那样,这只是我习惯指针以及为什么会发生崩溃的练习。感谢您的帮助。

最佳答案

Vehicle::Vehicle(VehiclePart* vehiclePart, int VehiclePartNumber)
{

请注意,您的构造函数有一个名为 vehiclePart 的参数。因此,

    vehiclePart = new VehiclePart(VehiclePartNumber);

这最终将构造函数的参数设置为 newed 类实例,而不是同名的类成员。

这与指针无关,但与作用域有关。

关于c++ - 尝试学习指针时练习程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37494732/

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