ostream方法不起作用

时间:2014-07-29 11:23:46

标签: c++ methods iostream

我有两个方法,第一个定义字符串:

我不明白为什么它没有成功以及我如何从主要方式调用此方法。

Actor::operator std::string( ) const {
    std::stringstream ss;
    ss << this->_id;
    std::string str1 = ss.str();

    std::stringstream s;
    s << this->_salary;
    std::string str2 = s.str();

    std::string str3 = "Actor first name = " + this->_firstname + ", last name = " + this->_lastname+", id = " + str1 + ", monthly salary = " + str2;
    if (this->_hasoscar==true)
        str3+=" was NOMINATED Oscar AWARD..";

    return str3;
}

下一个需要打印

const Actor& Actor::print(std::ostream& os) {
    os<< std::string();
    return *this;
}

2 个答案:

答案 0 :(得分:1)

不清楚为什么这样做是因为正常的工作方式是重载ostream操作符:

class Actor  {
public:
  friend std::ostream& operator<< (std::ostream& os, const Actor& a) {
    os << "Actor first name = " + a._firstname + 
          ", last name = " + a._lastname+", id = " + 
          a._id + ", monthly salary = " + a._salary;
    if (this->_hasoscar) {
       os << " was NOMINATED Oscar AWARD.."; 
    } 
    return os;
  }
};

通过这种方式,您可以轻松地创建和打印演员:

Actor a;
cout << a; 

第一种方法

Actor::operator std::string() const();

允许您从Actor到字符串的隐式转换,例如:

Person a;
std::string s = a;

答案 1 :(得分:1)

  

os<< std::string();

这不会将转换调用到string,它会创建一个临时字符串变量并将其写入流中,因此它等同于:

os << "";

要调用转换运算符,您需要告诉编译器您要将对象转换为字符串(而不仅仅是构造一个空字符串)。明确的方法是:

os << static_cast<std::string>(*this);

还有其他方法,例如:

os << std::string(*this);

os << (std::string)*this;

std::string s = *this;
os << s;

或者如果你喜欢不可读的代码,你可以明确地调用转换运算符:

os << this->operator std::string();

(最后一种方式并不是一个好主意。)

转换运算符的定义非常愚蠢,并且比它需要的速度慢得多。使用两个单独的字符串流以及字符串连接非常浪费,您可以使用单个字符串流完成所有操作:

Actor::operator std::string( ) const {
    std::stringstream ss;
    ss << "Actor first name = " << this->_firstname
       << ", last name = " << this->_lastname
       << ", id = " << this->_id
       << ", monthly salary = " << this->_salary;

    if (this->_hasoscar==true)
        ss << " was NOMINATED Oscar AWARD..";

    return ss.str();
}

然而,正如Velthune所说,除非你因其他原因需要转换为字符串,否则输出你的类的通常方法是为类重载operator<<