未创建默认构造函数时出错

问题描述 投票:0回答:1

作为我项目的一部分,我创建了一个参数化构造函数,但没有创建默认构造函数。当我创建该类的对象而不在“main()”方法中传递参数并尝试访问该类的成员函数时,会出现错误。如果我不创建任何构造函数或仅创建默认构造函数,则代码运行良好。我也尝试使用初始化列表进行相同的操作,但这不起作用。 完整代码如下:

#include<iostream>
using namespace std;
class worker
{
    public:
    string fname, lname;
    int salary;
    worker(int a)
    {
        salary=a;
    }
    void input()
    {
        cout<<"Enter your first name : ";
        cin>>fname;
        cout<<"Enter your last name : ";
        cin>>lname;
        cout<<"Enter your salary : ";
        cin>>salary;
    }
    void disp()
    {
        cout<<"\nName : "<<fname<<" "<<lname;
        cout<<"\nSalary : "<<salary<<"\n";
    }
    void raise()
    {
        salary +=(0.2*salary);
    }
    ~worker()
    {
        cout<<"\nDestructor called";
    }
};
int main()
{
    system("cls");
    cout<<"Welcome User!\n";
    //code snippet
    worker tp();//using "worker tp;" also shows error
    tp.input();
    return 0 ;
}

为什么需要创建默认构造函数,参数化还不够吗?如果我也不想使用参数化构造函数怎么办? 请指导我,因为我对 C++ 完全陌生

我希望我的代码能够在没有任何默认构造函数的情况下正常运行,但效果不佳。

c++ constructor compiler-errors syntax-error
1个回答
0
投票

一旦声明了自己的构造函数,C++ 就不会自动生成默认构造函数。毕竟,大多数时候您希望实际禁止用户使用未明确指定的构造函数。以下代码可以使用默认值:

#include<iostream>
using namespace std;
class worker
{
    public:
    string fname, lname;
    int salary;
    worker(int a)
    {
        salary=a;
    }
    void input()
    {
        cout<<"Enter your first name : ";
        cin>>fname;
        cout<<"Enter your last name : ";
        cin>>lname;
        cout<<"Enter your salary : ";
        cin>>salary;
    }
    void disp()
    {
        cout<<"\nName : "<<fname<<" "<<lname;
        cout<<"\nSalary : "<<salary<<"\n";
    }
    void raise()
    {
        salary +=(0.2*salary);
    }
    ~worker()
    {
        cout<<"\nDestructor called";
    }
};
int main()
{
    system("cls");
    cout<<"Welcome User!\n";
    //code snippet
    worker tp();//using "worker tp;" also shows error
    tp.input();
    return 0 ;
}
© www.soinside.com 2019 - 2024. All rights reserved.