编写程序以
->创建一个“雇员”类,并以数据成员的姓名,名称以及基本薪水和总薪水为基础。
->创建成员函数,例如读取数据的getdata函数和显示详细信息的showdata函数。
->创建sum()作为朋友函数来计算工资总额。
BS =基本工资
gs = basic_salary + 0.5 * basic_salary + 0.9 * basic_salary;
我的代码有问题。 get_gs()函数始终返回0。我的错误是什么?
我也删除了先前的.exe后再次运行它,出现了编译器错误。但它保持不变。
#include <iostream>
using namespace std;
class employee
{
string name;
string designation;
double bs;
double gs;
public:
employee()
{
}
employee(string _name, string des, double _bs)
{
name = _name;
designation = des;
bs = _bs;
}
void set(string _name, string des, double _bs)
{
employee(_name, des, _bs);
}
double get_gs()
{
double gs;
gs=bs + (0.5 * bs) + (0.9 * bs);
return gs;
}
};
int main()
{
employee *e = new employee;
string name, desti;
double bs, gs;
cout << "Enter name destiny basic_salary " << endl;
cin >> name >> desti >> bs;
e->set(name, desti, bs);
gs=e->get_gs();
cout << "the Gross salary :" << gs << endl;
return 0;
}
答案 0 :(得分:2)
在代码中带有注释的解决方案:
#include <iostream>
// using namespace std; // not a good practise
class employee {
std::string name;
std::string designation;
double bs;
// double gs; // wasn't used so remove it
public:
// initialize values like this, and pass strings as "const&":
employee(const std::string& _name, const std::string& des, double _bs) :
name(_name), designation(des), bs(_bs)
{}
employee() : employee("", "", 0) {} // delegate to first constructor
void set(const std::string& _name, const std::string des&, double _bs) {
// your old set() created a temporary employee that
// wasn't used for anything and then it was destroyed
name = _name;
designation = des;
bs = _bs;
}
// make member functions that does not change the state of "this" const
double get_gs() const { return bs + (0.5 * bs) + (0.9 * bs); }
};
int main() {
employee e; // no need for new, create it like any other variable
std::string name, desti;
double bs, gs;
std::cout << "Enter name destiny basic_salary\n";
std::cin >> name >> desti >> bs;
e.set(name, desti, bs);
gs = e.get_gs();
std::cout << "the Gross salary : " << gs << "\n";
}
答案 1 :(得分:2)
在您的set()
方法中,调用employee(_name, des, _bs);
创建一个新的临时employee
对象,然后将其立即丢弃。它不会像您期望的那样更新调用employee
的{{1}}对象的成员。因此,set()
成员永远不会被分配一个值。
尝试以下方法:
bs
或者:
#include <iostream>
using namespace std;
class employee
{
string name;
string designation;
double bs;
public:
employee() : bs(0.0) { }
employee(string _name, string des, double _bs)
: name(_name), designation(des), bs(_bs)
{
}
void set(string _name, string des, double _bs)
{
name = _name;
designation = des;
bs = _bs;
}
double get_gs() const
{
return bs + (0.5 * bs) + (0.9 * bs);
}
};
int main()
{
employee e;
string name, desti;
double bs, gs;
cout << "Enter name destiny basic_salary " << endl;
cin >> name >> desti >> bs;
e.set(name, desti, bs);
gs = e.get_gs();
cout << "the Gross salary :" << gs << endl;
return 0;
}