在C++有参构造和无参构造调用中遇到问题,想请教是什么原因造成的?(刚开始学)代码如下:
#include <iostream>
#include <string>
using namespace std;
class studet{
public:
int age;
string name;
// bool set (int a);
// bool set (string a);
studet();
studet(int a ,string b);
};
studet ::studet()
{
age = 20;
name = "张三";
};
studet ::studet(int a, string b){
age = a;
name = b;
};
void test1()
{
studet aa;
cout << aa.age << endl;
cout << aa.name<< endl;
cout<<"无参构造"<<endl;
};
void test2(int a, string b)
{
studet bb();
cout << bb.age << endl;
cout << bb.name<< endl;
cout<<"有参构造"<<endl;
};
int main()
{
test1();
test2(30, "z李四");
return 0;
}
在有参构造中输出bb.age和name时报错,把这两行注释掉能显示有参构造
运行时错误:
注释后: