【问题标题】:C++ - Initializing class member with an instanceC++ - 用实例初始化类成员
【发布时间】:2012-10-15 19:44:03
【问题描述】:

我的问题如下:假设我有:

class Foo
{
public:
    Foo() {}
    void setInt(int i) { myInt = i; }
    int getInt() { return myInt; }
private:
    int myInt;
};

class Bar
{
public:
    Bar(Foo f) { /* do something with f.getInt() */ }
};

现在我有另一个类,其中 Bar 作为成员变量:

class BarUser
{
public:
    BarUser();
private:
    Bar bar;
};

我想编写 BarUser 的构造函数,但是我想用 Foo 成员初始化 Bar,该成员的整数为 3。即:

Foo f;
f.setInt(3);
Bar b(f);

但是,由于我有 Bar 作为类成员,我无法将所有这些代码都写在初始化列表中......我的意思是:

BarUser::BarUser() : bar(/* Foo after executing f.setInt(3) */)
{ ... }

假设 Bar 不允许赋值运算符 - 我如何按预期初始化它?

谢谢!

【问题讨论】:

    标签: c++ class initialization-list


    【解决方案1】:

    如果不能改Foo,写一个函数:

    Foo make_foo(int i) { 
         Foo f; 
         f.setInt(i); 
         return f;
    }
    

    然后用bar(make_foo(3))初始化。

    给Foo 一个构造函数但没有int 构造函数,你有点自取其辱。您最好将explicit 构造函数添加到Foo,它采用int。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2015-05-18
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多