Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;-使用实例初始化类成员_C++_Class_Initialization List - Fatal编程技术网

C++ C++;-使用实例初始化类成员

C++ C++;-使用实例初始化类成员,c++,class,initialization-list,C++,Class,Initialization List,我的问题如下:假设我有: 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作为成员Varabl

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

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作为成员Varable:

class BarUser
{
public:
    BarUser();
private:
    Bar bar;
};
我想写BarUser的构造函数,但是我想用一个以3为整数的Foo成员初始化Bar。即:

Foo f;
f.setInt(3);
Bar b(f);
但是,由于我将Bar作为类成员,我无法在初始化列表中编写所有这些代码。。。我的意思是:

BarUser::BarUser() : bar(/* Foo after executing f.setInt(3) */)
{ ... }
假设Bar不允许赋值运算符-如何按预期初始化它


谢谢

如果无法更改
Foo
,请编写一个函数:

Foo make_foo(int i) { 
     Foo f; 
     f.setInt(i); 
     return f;
}
然后用
条初始化(make_foo(3))

你给了
Foo
一个构造函数,却没有
int
构造函数,这有点像是在砸自己的脚。您最好向
Foo
添加一个
explicit
构造函数,该构造函数接受
int