Bil*_*nch 11
让我们创建一个看起来像cout(但没有那么多铃声和口哨声)的类.
#include <string>
class os_t {
public:
os_t & operator<<(std::string const & s) {
printf("%s", s.c_str());
return *this;
}
};
int main() {
os_t os;
os << "hello\n";
os << "chaining " << "works too." << "\n";
}
Run Code Online (Sandbox Code Playgroud)
笔记:
operator<<是一个运算符重载就像operator+所有其他运算符一样.return *this;.os_t因为其他人写的而不能改变课程该怎么办?我们不必使用成员函数来定义此功能.我们也可以使用免费功能.让我们展示一下:
#include <string>
class os_t {
public:
os_t & operator<<(std::string const & s) {
printf("%s", s.c_str());
return *this;
}
};
os_t & operator<<(os_t & os, int x) {
printf("%d", x);
return os;
// We could also have used the class's functionality to do this:
// os << std::to_string(x);
// return os;
}
int main() {
os_t os;
os << "now we can also print integers: " << 3 << "\n";
}
Run Code Online (Sandbox Code Playgroud)
在GMP库中可以找到这种逻辑如何有用的一个很好的例子.该库旨在允许任意大的整数.我们通过使用自定义类来完成此操作.这是一个使用它的例子.请注意,运算符重载让我们编写的代码看起来几乎与我们使用传统int类型相同.
#include <iostream>
#include <gmpxx.h>
int main() {
mpz_class x("7612058254738945");
mpz_class y("9263591128439081");
x = x + y * y;
y = x << 2;
std::cout << x + y << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
<< 是C ++中的二进制运算符,因此可以重载。
您知道此运算符的C用法,其中1 << 3的二进制操作返回8。您可以将其视为int operator<<(int, int)传递参数1和3返回值的方法8。
从技术上讲,operator<<可以做任何事情。这只是一个任意方法调用。
按照C ++中的约定,该<<运算符除用作位移运算符外,还用于处理流。执行时cout << "Hello!",您将调用带有prototype的方法ostream & operator<< (ostream & output, char const * stream_me)。注意返回值ostream &。该返回值允许您多次调用该方法,就像std::cout << "Hello World" << "!";调用operator<<两次一样……一次在std :: cout和“ Hello World”上,第二次在第一次调用和“!”的结果上进行。
通常,如果要创建一个名为的类class Foo,并且希望它是可打印的,则可以将打印方法定义为ostream & operator<< (ostream & output, Foo const & print_me)。这是一个简单的例子。
#include <iostream>
struct Circle {
float x, y;
float radius;
};
std::ostream & operator<< (std::ostream & output, Circle const & print_me) {
output << "A circle at (" << print_me.x << ", " << print_me.y << ") with radius " << print_me.radius << ".";
}
int main (void) {
Circle my_circle;
my_circle.x = 5;
my_circle.y = 10;
my_circle.radius = 20;
std::cout << my_circle << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)