【问题标题】:Not able to modify class composite data members无法修改类复合数据成员
【发布时间】:2020-11-23 21:54:42
【问题描述】:

我的程序中有3 类,它们相互交互并包含彼此的实例:

class Inventory 
{
public:
   // Increment Data Members
   void incrementHerbs() { herbs++; }
   void incrementHealth() { health++; }
   void incrementGold() { gold++; }

   // Getters
   int getHerbs() { return herbs; }
   int getHealth() { return health; }
   int getGold() { return gold; }

private:
   int herbs = 0;
   int health = 3;
   int gold = 0;
};

class Player 
{
public:
   void setRow(int row) { this->rowCoordinate = row; }
   void setCol(int col) { this->colCoordinate = col; }
   int getRow() { return rowCoordinate; }
   int getCol() { return colCoordinate; }
   Inventory getBag() { return Bag; }

private:
   int rowCoordinate;
   int colCoordinate;
   Inventory Bag;
};

class Board
{
public:
   int getNumRows() { return numRows; }
   int getNumCols() { return numCols; }
   Player getPlayer() { return User; }

private:
   int numRows;
   int numCols;
   char** maze;
   Player User;
};

我只是在main 函数中实例化一个Board 对象。在我的程序中,我希望能够通过该对象增加库存类中的herb 计数。

我已经尝试过:

Board board;
board.getPlayer().getBag().incrementHerbs();

这个调用编译没有任何错误,但是当我打印出 herb 计数时,herb 计数仍然相同。

它没有增加。可能出了什么问题,我该怎么办?

【问题讨论】:

  • 那是因为您按值返回包,这意味着当您调用 incremenetHerbs 时,您正在修改玩家包的 副本,而不是他们的实际包。您应该使用参考资料(如果您不了解它们,现在是个好时机!)
  • 您的Board 类不扩展Inventory,也不包含Inventory 成员。它怎么可能知道Inventory 的某个不相关实例是否改变了它的herb 计数?

标签: c++ class oop member member-functions


【解决方案1】:

可能出了什么问题,我该怎么办?

在您的Player 类中,您的getBag() 函数返回Inventory 的副本(即成员Bag)。

Inventory getBag() { return Bag; }
//^^^^^^----> is copy!

您需要返回引用才能修改它

Inventory& getBag() { return Bag; }
//^^^^^^^^

Board 的函数 getPlayer() 也存在同样的问题

Player getPlayer() { return User; }
//^^^^----> is copy!

你需要

Player& getPlayer() { return User; }
//^^^^^^

这是demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多