【问题标题】:C++ toString outputs integerC++ toString 输出整数
【发布时间】:2013-01-12 00:27:34
【问题描述】:

我正在复习我的 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;
}

【问题讨论】:

  • std::ostreamsprintf...尴尬的组合
  • 建议不要混合使用 iosteam 和 stdio。 stdio 属于 c 并且它不是 OOP iostream 为您提供对象。坚持 iostream

标签: c++ operator-overloading tostring


【解决方案1】:

sprintf 返回:

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

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

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

虽然你最好坚持使用 streams 而不是混合使用 CC++ 标准库:

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

【讨论】:

  • 详细说明 - 你不应该在 C++ 中使用sprintf;这是不安全的,最好用stringstream代替。
  • 该死,这是一个简单的修复。谢谢。
【解决方案2】:

这真的不是 ostreams 的工作方式。事实上,如果您查看 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 不是一个好主意,但至少可以让您的代码正常工作。

【讨论】:

    【解决方案3】:

    把C/C++代码混在一起是不好的做法,只写纯c++代码,

    std::ostream& operator<<(std::ostream &strm, const Employee &e) 
    {  
      strm << "Name: " << e.name << " Salary: $" << std::setprecision(2) << e.getPay();
      return strm;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2015-12-06
      • 2017-01-10
      • 1970-01-01
      相关资源
      最近更新 更多