C++工程,输出运算符重载,输出运算符重载类外定义、类内定义,输出运算符重载结构体内定义、结构体外定义

文章目录

  • 1,输出运算符重载,结构体外定义
  • 2,输出运算符重载,结构体内定义
  • 3,输出运算符重载,类外定义
  • 4,输出运算符重载,类内定义
  • 5,编译运行效果都一样

1,输出运算符重载,结构体外定义

在这里插入图片描述

#include 

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 

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 

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 

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,编译运行效果都一样

在这里插入图片描述

你可能感兴趣的:(C++工程)