【问题标题】:Object constructor within another constructor?另一个构造函数中的对象构造函数?
【发布时间】:2020-04-20 00:12:36
【问题描述】:

我对 CPP 还是很陌生,我正在利用我们目前的所有空闲时间尝试新事物。我有 2 个单独的类,我想在 main 中为这两个类创建一个初始化列表......也许我没有用最好的话说,但是......

有这个:

class Status
{
public:
    int x, y;
    float angle;
    unsigned short hp;
    bool isActive;
    Status(const int _x, const int _y, const float _angle, const unsigned short _hp, bool _isActive)
        : x(_x), y(_y), angle(_angle), hp(_hp), isActive(_isActive){};
};

还有这个:

class Hero
{
    std::string name;
    Status status;
    Hero(const std::string _name, Status &status)
        : name(_name), status(x, y, angle, hp, isActive){}; 
    void display()
    {
        std::cout << "Hero:\t" << name << std::endl;
        std::cout << "HP:\t" << Hero::status.hp << std::endl;
        std::cout << "Hero is " << Hero::status.isActive ? " active" : " inactive";
        std::cout << std::endl;
    };

...我最终想做这样的事情... Hero h = {"Iron Man", {1, 2, 32.9, 100, true}};

请指导我,哦,聪明的人......

【问题讨论】:

  • Hero 构造函数不会编译。它引用了未在该范围内声明的名称xy 等。
  • ...如何设置 Hero 类构造函数以在实例化时将 hero 和 status 成员设置在初始化列表中。

标签: c++ object constructor initializer-list


【解决方案1】:

这段代码:

Hero(const std::string _name, Status &status)
    : name(_name), status(x, y, angle, hp, isActive){}; 

应该是:

Hero(const std::string _name, Status status)
    : name(_name), status(status){};

也可以是status(std::move(status))

还有一个逻辑错误,条件运算符的优先级高于&lt;&lt;,所以你需要一些括号。

【讨论】:

    【解决方案2】:

    两个问题:

    1. 首先你不能直接使用Status 成员变量。要解决这个问题,您需要像

      那样正常访问它们
      Hero(const std::string _name, Status &_status)
          : name(_name), status(_status.x, _status.y, _status.angle, _status.hp, _status.isActive)
      {}
      

      或者您可以只依赖自动生成的复制构造函数:

      Hero(const std::string _name, Status &_status)
          : name(_name), status(_status)
      {}
      
    2. 第二个问题是表达式{1, 2, 32.9, 100, true} 导致了一个所谓的rvalue,它不能被普通引用捕获。您要么需要使用右值引用、const 引用,要么需要使用普通的非引用值。我真的推荐后者:

      Hero(const std::string _name, Status _status)
          : name(_name), status(_status)
      {}
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 2018-11-17
      • 2020-11-18
      • 2015-07-02
      相关资源
      最近更新 更多