1,输出运算符重载,结构体外定义
#include <iostream>
struct Point {
int x = 0;
int y = 0;
Point() {};
Point(int a, int b) {x=a; y=b;};
};
std::ostream &operator<<(std::ostream &os, const Point &rhs) {
os << "x:" << rhs.x << " y:" << rhs.y;
return os;
};
int main() {
Point point(1,2);
std::cout << point;
std::cout << std::endl;
return 0;
}
2,输出运算符重载,结构体内定义
#include <iostream>
struct Point {
int x = 0;
int y = 0;
Point() {};
Point(int a, int b) {x=a; y=b;};
std::ostream &operator<<(std::ostream &os) {return (os << "x:" << x << " y:" << y);};
};
int main() {
Point point(1,2);
point << std::cout;
std::cout << std::endl;
return 0;
}
3,输出运算符重载,类外定义
要将输出运算符重载申明为类的友元函数
#include <iostream>
class Point {
private:
int x = 0;
int y = 0;
public:
Point() {};
Point(int a, int b) {x=a; y=b;};
friend std::ostream &operator<<(std::ostream &os, const Point &rhs);
};
std::ostream &operator<<(std::ostream &os, const Point &rhs) {
os << "x:" << rhs.x << " y:" << rhs.y;
return os;
};
int main() {
Point point(1,2);
std::cout << point;
std::cout << std::endl;
return 0;
}
4,输出运算符重载,类内定义
#include <iostream>
class Point {
private:
int x = 0;
int y = 0;
public:
Point() {};
Point(int a, int b) {x=a; y=b;};
std::ostream &operator<<(std::ostream &os) {return (os << "x:" << x << " y:" << y);};
};
int main() {
Point point(1,2);
point << std::cout;
std::cout << std::endl;
return 0;
}
5,编译运行效果都一样