【问题标题】:Cout calls a method with operator <<Cout 使用运算符 << 调用方法
【发布时间】:2020-11-17 01:35:07
【问题描述】:
#include <iostream> 
using namespace std; 

int main() 
{ 
    char sample[] = "something really weird about c++"; 
    cout << sample << " - huh?"; 
    return 0; 
}

这是一个简单的 c++ 代码,可以在屏幕上打印一些东西,因为我来自 python,对我来说,一个对象(根据各种来源'cout' 是类 ostream 的对象)似乎真的很奇怪我只是想知道对象如何输出屏幕上的某些东西或在不调用任何方法的情况下执行语句和函数之类的操作,我最好的猜测 的情况下相乘一些值

【问题讨论】:

  • 与您输入的相同:cout.operator&lt;&lt;(sample).operator&lt;&lt;(" - huh?"); &lt;&lt; 只是方法调用的语法糖。

标签: c++


【解决方案1】:

在 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;
}

请注意,运算符不一定是成员。有些只能作为会员强硬实施。更多关于 C++ 中的运算符重载:What are the basic rules and idioms for operator overloading?


根据您的具体要求

如果我是对的,您是否希望通过重载 来创建一个对象来执行类似“cout”的操作,例如将某个值相乘[不调用方法或]

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*= 会更自然,因为这是预期在给定对象上乘以某些东西的运算符。

【讨论】:

    猜你喜欢
    • 2021-08-20
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-26
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多