我有class car
,并且我使用car作为class App
中的属性。
class Car{
private:
string color;
public:
//setter getter
void setColor(string c){
color = c;
}
string getColor(){
return color;
}
}
和
class App(){
private:
Car car;
public:
App():car(){
}
Car getCar(){
return car;
}
}
这是我的主要应用
int main(){
App app[2];
app[0].getCar().setColor("red")
//WHY RETURN NULL?
cout << app[0]/getCar().getColor();
return 0;
}
setter 运行良好,但为什么 getter 返回 null,就好像对象 app[0]
是重新实例一样?
谢谢您
最佳答案
the setter is working well but, why the getter is return null like the object (app[0]) is reinstance?
您遇到问题,因为您正在返回 Car
的临时拷贝成员变量而不是对成员变量本身的引用。更具体地说,您的成员函数 getCar()
返回Car
而不是Car&
。您当前的版本将复制成员变量 car
的值转换为临时变量并返回临时变量作为其返回值,而不是成员变量本身。那么在这段代码中:
app[0].getCar().setColor("red");
您实际上正在修改 getCar()
的临时拷贝的内容回。由于这是一个临时拷贝,因此临时拷贝将在语句结束时被销毁,并且您的所有修改都将丢失。此外,car
app[0]
的成员变量将继续保留其默认值。
您想要的是返回对成员变量本身的引用,这将允许您直接编辑其内容。为此,您需要修改 App
类如下:
class App(){
private:
Car car;
public:
App():car(){
}
Car& getCar(){
return car;
}
}
现在getCar()
返回对成员变量 car
的引用,修改此引用将直接修改 car
app[0]
的成员变量,为您提供预期的行为。
关于c++ - Getter 返回 null C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49001640/