C++有参构造和无参构造

在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时报错,把这两行注释掉能显示有参构造
运行时错误:

img


注释后:

img

把 bb() 的括号去掉,编译器会默认把这个识别为函数。

img

set 是一个内置的类名,你这里没有写所谓的有参构造函数

studet bb(a, b); 这样才行

#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(a, b);
    cout << bb.age << endl; 
    cout << bb.name<< endl;
    cout<<"有参构造"<<endl;
};
 
int main()
{
    test1();
    test2(30, "z李四");
    return 0;
}

img