关于封闭类的构造函数问题

#include <iostream>
using namespace std;
class Base {
public:
    int k;
    Base(int n):k(n) { }
};
class Big {
public:
    int v; Base b;
// 在此处补充的代码
};
int main() {
    Big a1(5); Big a2 = a1;
    cout << a1.v << "," << a1.b.k << endl;
    cout << a2.v << "," << a2.b.k << endl;
    return 0;
}`

要求输出
5,5
5,5
请教一下应该怎么写 谢谢

阅读 3.7k
2 个回答

其实只要写一行

Big(int n) : b(n), v(n) {}

就行了啊,不需要为 Base 添加额外的构造函数,直接在成员构造列表里用已有的构造函数构造 Base 就行了。

update

1.Executable code

#include <iostream>
using namespace std;
class Base {
public:
    Base(){k=0;};    //default constructor
    Base(int n):k(n) { }
    ~Base(){};    //destructor
    int k;
};
class Big {
public:
    Big(){v=0;};   //default constructor
    /*****the constructor you may want*****/
    Big(int n):v(n),b(n){};
    ~Big(){};
    int v; 
    Base b;
};
int main(void) {
    Big a1(5); 
    Big a2 = a1;
    cout << a1.v << "," << a1.b.k << endl;
    cout << a2.v << "," << a2.b.k << endl;
    return 0;
}

2.some supplementary instruction

From the main function, we can see that you want to use a constructor to initialize v and k equal to 5,so I write a constructor Big(int n) to initialize them.
p.s. I add default constructor just because If we define any constructors, the class will not have a default constructor unless we define that constructor ourselves.So just in case,I add default constructor to initialize v and k to 0.If you just want to solve this problem,these default constructors are unnecessary.
p.s.2 I strongly suggest you declare v and k as private variables and add some function to set/get these variables,since it could be safer.
update:Of course,as Axurez says,we can use the constructor of Base.That's better.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题