我正在刷我的C ++,我试图找出为什么我的toString函数没有输出我定义的格式化字符串。
我所指的功能是:friend std::ostream& operator<<(std::ostream&, const Employee&);
Employee.cpp
#include <iostream>
#include <stdio.h>
using namespace std;
class Employee {
private:
string name;
double rate;
double hours;
double getPay() const;
friend std::ostream& operator<<(std::ostream&, const Employee&);
public:
Employee(string, double);
void setHours(double);
};
Employee::Employee(string name, double rate) {
this->name = name;
this->rate = rate;
this->hours = 0;
}
void Employee::setHours(double hours) {
this->hours = hours;
}
double Employee::getPay() const {
double gross = this->hours * this->rate;
double overtime = this->hours > 40 ?
(this->hours - 40) * (this->rate * 1.5) : 0;
return gross + overtime;
}
// toString
std::ostream& operator<<(std::ostream &strm, const Employee &e) {
char buff[64];
return strm << sprintf(buff, "Name: %s, Salary: $%.2f\n",
e.name.c_str(), e.getPay());
}
int main (int* argc, char** argv) {
Employee emp1("Bob", 28);
Employee emp2("Joe", 32);
emp1.setHours(44);
emp2.setHours(25);
cout << emp1 << endl;
cout << emp2 << endl;
return 0;
}
答案 0 :(得分:6)
sprintf
返回:
在任何情况下都不返回字符串,它总是返回int
,这就是您要求打印的内容。大概你想要这个:
char buff[64];
sprintf(buff, "Name: %s, Salary: $%.2f\n",
e.name.c_str(), e.getPay());
return strm << buff;
虽然如果你坚持 streams 而不是混合 C 和 C ++ 标准库会更好:
return strm << "Name: " << e.name << ", Salary: $" << std::setprecision(2) << e.getPay() << "\n";
答案 1 :(得分:2)
这真的不是ostream的工作方式。事实上,如果你查找sprintf,你会发现你实际上并不想将其返回值打印到strm。相反,你应该打印buf。类似的东西:
std::ostream& operator<<(std::ostream &strm, const Employee &e) {
char buff[64];
sprintf(buff, "Name: %s, Salary: $%.2f\n",
e.name.c_str(), e.getPay());
return strm << buff;
}
将sprintf和ostream混合起来并不是一个好主意,但至少会使你的代码工作。
答案 2 :(得分:1)
将C / C ++代码混合在一起,编写纯c ++代码
是不好的做法std::ostream& operator<<(std::ostream &strm, const Employee &e)
{
strm << "Name: " << e.name << " Salary: $" << std::setprecision(2) << e.getPay();
return strm;
}