gpt4 book ai didi

c++ - 我应该采取什么步骤来用普通变量替换指针的出现?

转载 作者:太空宇宙 更新时间:2023-11-03 10:44:46 27 4
gpt4 key购买 nike

参加以下 Seat 类(class):

class Seat
{
Passenger* passenger; // I'd like this to be Passenger passenger;
}

如果我去掉星号,我应该如何更新下面的方法?

bool initSeat()
{
passenger = NULL; // &passenger = NULL; does not compile as it's not a reference type.
return passenger == NULL; // Is there even a need to allocate memory? Maybe have the method blank?
}

bool insertSeat(Passenger* p)
{
bool bsuccess = TRUE;
if (p != NULL)
{
if (passenger == NULL) // replace with &passenger
passenger = p; // replacing with &passenger doesn't compile
else
bsuccess = FALSE;
}
else
passenger = NULL; // again, prefixing the & doesn't compile (that'd make it a reference type) so how do I set the pointer to NULL?
return bsuccess;
}

我可能会感到困惑,因为我缺少一些基本概念。

最佳答案

编辑版本。阅读我的评论:

class Seat
{
Passenger passenger;
}

不需要 InitSeat,因为 passenger 将由 Passenger 类的构造函数初始化。

//bool initSeat()
//{
// passenger = NULL;
//return passenger == NULL;
//}

假设,你只会得到一个指针作为参数:

bool insertSeat(Passenger* p)
{
bool bsuccess = TRUE;
if (p != NULL)
{
passenger = *p; // dereference the pointer directly

}
else {

passenger = Passenger(); // Might not be needed, but if needed make sure the assignment operator is properly(operator=) implemented
}
return bsuccess;
}

基本上,您需要复习一下指针的内容和基本的类设计。

关于c++ - 我应该采取什么步骤来用普通变量替换指针的出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24719922/

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