weixin_67207019 2023-06-22 13:05 采纳率: 0%
浏览 25

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

  • 写回答

3条回答 默认 最新

  • P2441M 2023-06-22 13:10
    关注

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

    评论

报告相同问题?

问题事件

  • 修改了问题 6月22日
  • 创建了问题 6月22日