c++ - 如果在重载的输出运算符函数中使用 cout 怎么办?

标签 c++ operator-overloading cout

我有以下代码,其中包含重载输出运算符:

class Student 
{
public:
    string name;
    int age;
    Student():name("abc"), age(20){}
    friend ostream& operator<<(ostream&, const Student&);
};
ostream& operator<<(ostream& os, const Student& s)
{
    os << s.name; // Line 1
    return os;
}

我想知道如果我改变了有什么区别 Line 1进入这个:cout << s.name

最佳答案

然后 operator <<会宣传它可以将学生的名字输出到任何流,但忽略它的参数并始终输出到标准输出。打个比方,这类似于写作

int multiplyByTwo(int number) {
    return 4;
}

可以看出,这肯定是有问题的。如果你真的想一直返回 4,那么函数应该是

int multiplyTwoByTwo() {
    return 4;
}

当然你做不到operator <<只接受一个参数,因为它是一个二元运算符,所以这就是类比失效的地方,但你明白了。

关于c++ - 如果在重载的输出运算符函数中使用 cout 怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10481256/

相关文章:

c++ - 有没有一种方法可以在不使用命名空间 std 或以 std::为前缀的情况下引用 cout?

c++ - 非静态成员函数的无效使用c++线程linux

c++ - 如何打印元组 vector ?

c++ - 如何在 Atmel Studio 6 中为 C++ 更改 avr32-gcc C 编译器而无需创建新项目?

c++ - 为什么 `printf("%llu\n", 1ull << n) ;` and ` printf ("%llu\n", 1ull << 64);` 的输出在 C++ 中不同?(n=64)

C++从左向右重载[]

c++ - 重载运算符 ()

python - __radd__ 可以按任何顺序使用操作数吗?

c++ - 使用 << 运算符同时写入文件和 cout

C++ 异常阻止 cout 打印