C ++编程 [英] c++programming

查看:110
本文介绍了C ++编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class payroll
{
    float salary;
public:
    payroll(float f)
    {
        salary=f;
    }
    void show_salary()
    {
        cout<<"salary="<<salary;
    }
    payroll operator+(payroll);
};
payroll payroll::operator +(payroll p)
{
    payroll p2;
    p2.salary=salary+p.salary;
    return p2;
}
void main()
{
    payroll anil(1200),deepak(1300),acct;
    acct=anil+deepak;
    acct.show_salary();
}


出现错误:没有合适的默认构造函数.


getting error : no appropriate default constructor available.

推荐答案

错误消息告诉您.您没有没有参数*的构造函数payroll(),但是您试图在代码的两个位置隐式调用一个.如果添加行
The error message tells you. You don''t have a constructor payroll() with no arguments*, yet you are trying to implicitly call one at two places in your code. If you add the lines
payroll()
{
  salary = 0.0;
}

到您的班级(例如,在operator+的定义之前),那么它应该都可以工作.

*没有参数的构造函数称为默认构造函数.

彼得
投票答案,并在适当的情况下标记为接受.

to your class (say, before the definition of operator+), then it should all work.

* A constructor with no arguments is called a default constructor.

Peter
Vote for answers, and mark accepted if appropriate.


Peter_in_2780正在读我的思想.
如果您将代码编码为payroll p2(salary+p.salary);,则没有参数的构造函数payroll()也是不必要的.默认构造函数用于诸如payroll p2;的语句.
Peter_in_2780 is reading my mind.
And a constructor payroll() without arguments is not necessary if you code as payroll p2(salary+p.salary);. The default constructor is for statements like payroll p2;.


您只有以下构造函数:
You only have the following constructor:
payroll:payroll(float f)



这意味着您的代码中没有以下实例化:



This means that out of the following instantiations in your code:

payroll anil(1200),deepak(1300),acct;


只有前两个有效.

前两个是有效的,因为我在上面引用的构造函数有一个float参数.
您可以删除最后一个:


only the first two are valid.

The first two are valid because of the constructor I quoted above has a float parameter.
You can either remove the last one:

payroll anil(1200), deepak(1300)


或添加默认构造函数:


or add a default constructor:

class payroll
{
    float salary;
public:
    payroll()
    {
        salary=0.0f;
    }
    payroll(float f)
    {
        salary=f;
    }
    void show_salary()
    {
        cout<<"salary="<<salary;
    }
    payroll operator+(payroll);
};



注意:如果您没有任何构造函数,则编译器会添加一个默认的构造函数,但是由于您拥有一个默认的构造函数,因此不会麻烦,您必须自己编写它.
 



NOTE: If you hadn''t had any constructors the compiler would have added a default constructor, but since you have one it doesn''t bother and you have to code it yourself.
 


这篇关于C ++编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆