gpt4 book ai didi

c++ - "Essential C++": Providing Class Instances of the iostream Operators

转载 作者:行者123 更新时间:2023-11-28 00:55:25 26 4
gpt4 key购买 nike

来自 Essential C++: 4.10 提供 iostream 运算符的类实例

Often, we wish to both read and write objects of a class. For example, to display our trian class object, we want to be able to write

cout << train << endl;

To support this, we must provide an overloaded instance of the output operator:

ostream& operator<< (ostream &os, const Triangular &rhs)
{
os << "(" << rhs.beg_pos() << "," << rhs.length() << ")";
rhs.display(rhs.length(), rhs.beg_pos(), os);
return os;
}

We return the same ostream object passed into the function. This allows multiple outptu operators to be concatenated. Both objects are passed by reference. The ostream operand is not declared as const because each output operation modifies the internal state of the ostream object.

我有点困惑为什么不能将 ostream 操作数声明为 const。如果输出运算符声明如下:

const ostream& operator<< (const ostream &os, const Triangular &rhs)

上面的声明有没有问题?

谢谢

最佳答案

问题是如果ostream参数(或相反 istream )是常量引用,则运算符(operator)将无法修改流对象。向流中插入/提取修改 流状态,因此现有 operator<<是非常量操作。这反过来意味着虽然您可以声明甚至定义:

std::ostream const & operator<<( std::ostream const & s, Type const & t );

问题是该定义根本无法写入任何内容到流中:

std::ostream const & operator<<( std::ostream const & s, Type const & t ) {
s << "Hi"; // Error: operator<<( std::ostream&, const char*) requires a
// non-const `std::ostream&`
return s; // This is fine
}

关于c++ - "Essential C++": Providing Class Instances of the iostream Operators,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11714045/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com