c++ - Getter 返回 null C++

标签 c++ oop mingw

我有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/

相关文章:

c++ - 奇怪的异常抛出 - 分配 : Operation not permitted

c++ - 移动一个 vector<T*> 到 vector<const T*>

c++ - 在 C++ gtk::drawarea 中:如何刷新图像

php - 仅当定义了其他类时才扩展 PHP 类

python - 将 .c 文件从 Cython 转换为独立的 .exe 和编译 gcc 错误

c++ - 为什么不能在外部定义嵌套类?

c++ - C++ 中的 friend 和模板

java - java中使用HashMap创建对象

javascript - 将子项连接到父项

windows - 使用干净的过滤器和 sed 在 git add 上更新文件