gpt4 book ai didi

c++ - 如何在两个类之间创建指针?

转载 作者:行者123 更新时间:2023-11-28 05:49:54 31 4
gpt4 key购买 nike

我想制作火车类和汽车类。我想在火车里放三节车厢。汽车彼此指向,因此我可以轻松地从一辆汽车到另一辆汽车。

class Train{   
// link other car, so i can go from one to another
// pointer to the engine

};
class car{
// cargo weight and pointer to next car and way to know we are in caboose
};

这是我做的:

main.cpp

#include <iostream>
#include "Train.h"
int main()
{
Train* engine;
car* cars = new car();
return 0;
}

头文件:

#ifndef TRAIN_H
#define TRAIN_H
class Train
{
public:
Train()
{
int* space = new int [3];
}

~Train();
};

class car
{
public:
int cargo_weight;
int wieght;
car()
{
int* number = new int [3];
}
~car();
car* Next;
private:
car* head;
car* tail;
};
#endif

最佳答案

首先,题外话:

Train(): firstCar(nullptr)
{
int* space = new int [3];
}

space 是一个指向 int 的指针。如果你想容纳 Car 并没有多大用处,但令人讨厌的是 space 只存在于 Train 的大括号内构造函数。它指向的三个整数都丢失了。不是删除或释放,而是丢失,并且没有指针告诉您在哪里可以找到这 3 个 int,很难释放它们的内存。这称为内存泄漏,通常被认为是糟糕的场景。

Next,Carheadtailnext。这使得 Car 既是链表元素又是链表。相当奇怪,可能没有必要。让 Train 充当链表。它有理由知道 Car 的链,而每辆车除了下一个,可能还有前一个 Car 之外,没有理由知道任何其他信息。

然后……

您似乎想在 Train 中将最多三个 Car 链接在一起。 Train 需要的第一件事是指向链中第一个 Car 的指针。

class Train
{
private:
Car * firstCar;
public:
Train(): firstCar(nullptr) // ensure that the first car point at a sentinel value
// otherwise we're in for a while world of hurt later
{
}

~Train();
};

并且您需要一种添加汽车的方法。

bool linkCar(Car * newcar)
{
if (firstCar != nullptr) // if there is no first car.
// See told you we'd need a sentinel!
{
firstCar = newcar; // this car is the first car
}
else
{
firstCar->linkCar(newcar); //tell the first car to link to the new car
}
}

这意味着 Car 需要一个 linkCar 方法

bool linkCar(Car * newcar)
{
if (next != nullptr) // if this car is the last car in the train add the new car here
{
next = newcar;
}
else
{ // not the last car. Keep looking until we find the last car
next->linkCar(newcar);
}
}

为了让它工作,Car::next 必须在构造函数中初始化为 nullptr

car():next(nullptr)
{
}

不幸的是,除非讲师要求您构建汽车的单链表,否则这种方法有点糟糕。一方面,您需要大量额外的簿记来阻止您添加第四辆车。您可能需要一堆额外的逻辑来释放您分配的所有汽车。您必须确保调用放车逻辑。而且,如果讲师想要一个双向链表,我上面的内容充其量只是提供了一个起点。幸运的是,在 Stack Overflow 上有数十个(如果不是数千个)如何构建双向链表的示例。

相反,存储一个 std::vector 汽车

class Train
{
private:
std::vector<Car> cars;
public:
Train()
{
}
bool addCar(Car &newcar)
{
if (cars.size() < 3)
{
cars.push_back(newcar);
}
}
};

请注意,我们不再需要析构函数,因为我们没有任何需要销毁的东西。 std::vector 为我们处理所有这一切。

汽车除了自己之外不需要知道任何事。不需要链接到下一辆车。不需要析构函数,因为所有 car 的资源都是 self 管理的。

class car
{
private:
int cargo_weight;
int weight;
public:
car()
{
}
};

可能应该扩展 car 构造函数来设置权重,以便每辆汽车都准备好开箱即用。

car(int c_weight, int car_weight): 
cargo_weight(c_weight),
weight(car_weight)
{
}

关于c++ - 如何在两个类之间创建指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473534/

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