【问题标题】:I am getting garbage value while using operator overloading我在使用运算符重载时得到垃圾值
【发布时间】:2021-08-05 08:29:36
【问题描述】:

我有一个问题-

编写一个 c++ 程序来计算 4 名员工的总薪水(净薪水+DA+TDS),其中 + 运算符重载以获得所有 4 名员工获得的总薪水。还可以通过运算符重载得到员工的平均工资。显示所有四名员工的所有详细信息。还显示谁的薪水最高。员工工资必须由用户在运行时输入。

#include<iostream>
#include<string>
using namespace std;
class Employee
{
    private:
        int net_salary, DA, TDA, Gross_salary;
    public:
        void SetData(int net, int da, int tda, int gross)
        {
            net_salary=net;
            DA=da;
            TDA=tda;
            Gross_salary=gross;
        }
        void GetData()
        {
            cout << "Enter net salary: "<<net_salary;
            DA = (15*net_salary)/100; //Declaring the value of DA as 15% and calculating the amount 
            //on basis of net salary of the employee
            TDA = (10*net_salary)/100; //Declaring the value of TDA as 10% and calculating the amount
            // of TDA on basis of net salary
            Gross_salary = net_salary+DA+TDA;
        }
        void DisplayData()
        {
            cout << "Total Gross Salary = "<<Gross_salary;
        }
        Employee operator +(Employee e)
        {
            Employee temp;
            temp.Gross_salary=Gross_salary+e.Gross_salary;
            return temp;
            }
};
int main()
{
    Employee e1,e2,e3,e4,e5;
    e1.GetData();
    e2.GetData();
    e3.GetData();
    e4.GetData();
    e5=e1+e2+e3+e4;
    e5.DisplayData();
    return 0;
}

【问题讨论】:

  • 你没有在任何地方调用 nSetData(),所以当operator+ 尝试使用它们时,你的数据成员没有分配给它们的值。

标签: c++ operator-overloading


【解决方案1】:

问题在于数据成员的初始值缺失。

// ...
cout << "Enter net salary: " << net_salary;
DA = (15*net_salary)/100;
// ...

这里,在GetData() 成员函数中,在您创建了五个e1,e2,e3,e4,e5Employee 类型的默认初始化对象后调用。这里的net_salary 是内置类型,默认由implicitly defined default constructor 初始化,因此它有一个未定义值。然后将此未定义的值分配给DAGetData() 正文中的值。

您不应该将SetData() 视为解决此问题的方法,因为它应该充当setter 方法,一种用于修改已经初始化的对象 的方法.您将需要为您的类实现构造函数,或者您至少可以为成员提供类内初始化程序,如下所示:

// ...
int net_salary=0, DA=0, TDA=0, Gross_salary=0;
// ...

我不禁注意到GetData() 要么有一个令人困惑的名称,要么试图做的事情超出了它的预期。它会进行一些内部计算,这对于 GetSomething 函数来说是可以的,但它会在进行一些打印时修改内部数据。

另外,请注意以下行(在GetData() 中):

Enter net salary: 

后面会跟着一个输出,您将没有机会在GetData() 中输入任何数据。我假设,您可能想要创建一个接受用户输入的构造函数,然后调用一个函数来完成所有需要的计算。

【讨论】:

  • 我按照你的建议初始化了值,但仍然没有得到想要的输出
  • @Vica 你期望输出什么?
  • 我必须从 4 个值中获取净工资,然后计算总价值并打印这 4 个员工的总工资总和
  • @Vica 那么你必须为对象提供所需的值,这与构造函数有关。
  • 我没听懂你在说什么?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-02
  • 1970-01-01
  • 2020-11-09
  • 2023-04-04
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多