【问题标题】:C++: Initializing class member variable with reference to another class member variable?C ++:参考另一个类成员变量初始化类成员变量?
【发布时间】:2018-11-09 20:21:32
【问题描述】:

我正在尝试在 C++ 中创建一个类,以存储多个参数的值,这些参数被组织为类“Planet”和“Satellite”类的成员变量,我想使用对'行星'。在这里,我提供了一个示例,其中我有一个“PlanetCatalog”类 成员变量“Planet neptune”和“Satellite triton”。

class Planet {
    public:

    double a;

    Planet() {}

    void setParams(  const double a_) {
        a = a_;
    }
};


class Satellite {
    public:

    double b;

    Planet & planet;
    Satellite( Planet & planet_):planet(planet_) { }

    void setParams(const double b_) {
        b = b_;
    }
}; 

class PlanetCatalog {

    public:

    Planet neptune;
    Satellite triton(neptune);

    void setAll() {
        neptune.setParams(1.);
        triton.setParams(2.);
    }

};

但是,在编译时我遇到了错误。

error: unknown type name 'neptune' 
    Satellite triton(neptune);

是否可以像我在这里所做的那样将行星和卫星存储为同一类的变量。如果没有,有人可以建议用 C++ 组织此功能的更好方法吗?

【问题讨论】:

  • 创建 PlanetCatalog 类的构造函数

标签: c++ constructor reference initialization


【解决方案1】:

使用括号进行类内初始化使编译器将triton 视为非静态成员函数声明,neptune 是第一个参数的类型,您应该使用 list-initialization 语法而是:

Satellite triton{neptune};

请注意,实际上不需要为此定义PlanetCatalog 构造函数。

【讨论】:

    【解决方案2】:

    发生了什么?

    class PlanetCatalog {
    public:
       ...
       Planet neptune;
       Satellite triton(neptune); //<-- Compiler sees this as a non-static member-function declaration
       ...
    

    由于该语句的上下文,编译器将其视为非静态成员函数声明,并尝试在相关的命名空间中找到名为 neptunetype );由于找不到它,它会发出错误。


    选项1:您可以在其member-initialization-list中定义一个为您初始化triton的构造函数

    class PlanetCatalog {
    public:
       ...
       Planet neptune;
       Satellite triton;
    
       PlanetCatalog() : triton(neptune) {}
       ...
    

    注意:使用这个选项,order of your class data members matters,因为数据成员的初始化顺序是由它们在类中的声明顺序定义的,而不是顺序member-initialization-list中的初始化


    选项 2:另一个直接的解决方案是使用 copy-initialization

    Satellite triton = neptune;
    

    选项 3:或list-initialization

    Satellite triton{neptune};
    

    选项 2 和 3 更可取,因为它隐式强制声明顺序。

    【讨论】:

    • 我不熟悉列表初始化,但它看起来像我想要的。但是,如果我只是将我的行替换为 'triton(neptune)' 到 'triton{neptune}'。我遇到以下错误:'错误:函数定义未声明参数'。在文档中,示例案例似乎使用相同的类(即 planetA{planetB} 而不是 SatelliteA{planetB} )对其进行初始化。这应该适用于我的情况吗?我不确定我错过了什么。
    • 您使用的是 C++11 吗? ...如果您没有使用 veey 最近的编译器,您可能需要在编译器的命令行调用中添加 -std=c++11 标志;或 IDE、构建文件等...如果您的编译器支持,您可以尝试更新的标准,例如 -std=c++14-std=c++17
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多