C++ toString输出整数

Mr.*_*irl 0 c++ operator-overloading tostring

我正在刷我的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;
}
Run Code Online (Sandbox Code Playgroud)

K-b*_*llo 6

sprintf 收益:

  • 成功时,返回写入的字符总数.此计数不包括自动附加在字符串末尾的附加空字符.
  • 失败时,返回负数.

在任何情况下它都不会返回一个字符串,它总是返回一个int,这就是你要求打印的内容.大概你想要这个:

char buff[64];
sprintf(buff, "Name: %s, Salary: $%.2f\n",
  e.name.c_str(), e.getPay());
return strm << buff;
Run Code Online (Sandbox Code Playgroud)

虽然如果你坚持使用流而不是混合使用C和C++标准库会更好:

return strm << "Name: " << e.name << ", Salary: $" << std::setprecision(2) << e.getPay() << "\n";
Run Code Online (Sandbox Code Playgroud)

  • 详细说明 - 你不应该在C++中使用`sprintf`; 它不安全,最好用`stringstream`取代. (2认同)