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