C++ 如何初始化类对象?
我有以下两个特定的课程:C++ 如何初始化类对象?,c++,class,initialization,C++,Class,Initialization,我有以下两个特定的课程: class foo{ private: int a; int b; public: foo(int x, int y) :a(x), b(y) { cout << "I just created a foo! << endl; } ~foo() { cout << "A foo was just destroyed!" <<
class foo{
private:
int a;
int b;
public:
foo(int x, int y)
:a(x), b(y)
{
cout << "I just created a foo! << endl;
}
~foo()
{
cout << "A foo was just destroyed!" << endl;
}
void set_a(int a_num)
{
a = a_num;
}
void set_b(int b_num)
{
b = b_num;
}
class bar{
private:
int T;
int S;
foo f;
public:
bar(int x, int y, foo n=(0,0) <--
:T(x), S(y), f(n)
{
cout << "I just created a f!" << endl;
foo.set_a(T); <--
foo.set_b(S); <--
}
~bar(){
cout << "A bar was destroyed!" << endl;
}
class-foo{
私人:
INTA;
int b;
公众:
foo(整数x,整数y)
:a(x),b(y)
{
cout您可以使用:
bar(int x, int y, foo n=foo(0,0)) : ... { ... }
如果您能够使用C++11编译器,还可以使用:
bar(int x, int y, foo n=foo{0,0}) : ... { ... }
及
而不是:
foo.set_a(T);
foo.set_b(S);
您需要使用:
f.set_a(T);
f.set_b(S);
因为您需要对成员变量f
调用set_a
和set_b
更好的选择是使用以下方法初始化f
:
bar(int x, int y} : T(x), S(y), f(x, y) {}
然后将构造函数的主体保留为空。bar(intx,inty,foon=(0,0)
=>bar(intx,inty,foon=foo(0,0)
这是可行的,但我希望下面的mutator方法也能得到它的值。另一个选项是:foon{0,0}
True,但是在bar内部创建的foo如何从bar类中获得值呢?(使用我标记的突变子)
bar(int x, int y} : T(x), S(y), f(x, y) {}