c++ - Cout 使用运算符 << 调用方法

标签 c++

#include <iostream> 
using namespace std; 

int main() 
{ 
    char sample[] = "something really weird about c++"; 
    cout << sample << " - huh?"; 
    return 0; 
}
这是在屏幕上打印一些东西的简单c++代码,因为我来自python,对我来说一个对象(根据各种来源'cout'是ostream类的对象)似乎真的很奇怪我只是想知道对象如何在屏幕上输出一些东西或者在不调用任何方法的情况下执行语句和函数之类的事情,我最好的猜测 << 在引擎盖下被重载并在其上调用方法,如果我是对的,你想创建一个执行类似“cout”的对象吗例如不调用方法或通过重载 <

最佳答案

同样在 Python 中,您可以重载运算符。例如,您可以实现特殊方法 __add__然后通过 a + b 调用它(参见例如here 了解详情)。原则上,如果您的问题是关于 Python 而不是 C++,那么答案不会有太大的不同。应用运算符就是调用函数。

cout << sample;
是一种简短的写作形式
cout.operator<<(sample);
即它调用cout的方法这是一个 std::ostream .

您可以为自定义类型的输出运算符提供重载,如下所示:
struct foo {};

std::ostream& operator<<(std::ostream& out, const foo& f) {
    // do something with out and f
    // expected is: write contents of f to out
    // possible is: anything
    return out;
}
请注意,运算符(operator)不一定是成员。有些只能作为成员(member)强硬实现。更多关于 C++ 中的运算符重载:What are the basic rules and idioms for operator overloading?

针对您的具体要求

if I'm right, would you like to make an object that that do something like 'cout' such as multiply some value [without calling a method or] by overloading <<?

struct multiplier {
    int value = 1;
    multiplier& operator<<(int x) {
        value *= x;
        return *this;
    }
 };

 multiplier m;
 m << 2 << 3 << 7;
 std::cout << m.value; // prints 42
但是,应谨慎使用运算符重载,并应牢记最小意外原则。在上面的例子中,重载 operator*= 会更自然。相反,因为那是期望在给定对象上乘以某些东西的运算符。

关于c++ - Cout 使用运算符 << 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64862593/

相关文章:

c++ - 这个左值返回危险吗?

c++ - libpng 错误 : read error (Visual Studio 2010)

c++ - 按内核线程增量

c++ - 为什么加载我的 SDF 会导致 Mobilizer 创建闭环错误

c++ - 为什么将 unique_ptr 与数组一起使用会导致编译错误?

c++ - STL::vector 无法分配内存 'randomly'

c++ - 具有一个显式参数的模板

C++:在派生类中扩展成员类型

c++ - Win32 确定键盘何时连接/断开连接

c++ - 在成员函数中返回 *this