#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/