cpp学习笔记3--class

class Complexs {
private:
    double real;
    double imag;

public:
    Complexs(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 运算符重载
    Complexs operator+(const Complexs& other) const {
        return Complexs(real + other.real, imag + other.imag);
    }

    // 输出运算符重载
    friend std::ostream& operator<<(std::ostream& os, const Complexs& c) {
        os << c.real << " + " << c.imag << "i";
        return os;
    }
};

首先,在 C++ 中,operator 是一个关键字,用于 ​​运算符重载​,使用格式是

ReturnType operator+(const MyClass& other) const {}

​这里operator后面有个+,是因为这个重载的是加法运算,重载后就可以做到Complex a, b; Complex c = a + b;直接将两个类相加,这里b是const Complex& other,c是return Complex,那么a是什么?为什么可以直接访问a的real、imag?其实是调用的 a.operator+(b),在operator函数内会有一个this指针,real=this->real,this就是a,而c并没有参与operator,只是作为它的返回值。所以说,在operator内的独立变量都是this的成员变量,既然private可以,那么public的成员函数是否也能通过operator访问呢?

Complexs operator+(const Complexs& other) const {
    print_real();
    return Complexs(real + other.real, imag + other.imag);
}

void print_real() const
{
    std::cout << real << std::endl;
}

答案是可以的,print_real输出的是a的。

至于下面的友函数,我们先看一个其他的函数

std::ostream& operator<<(std::ostream& os) {
    os << real << " + " << imag << "i";
    return os;
}

据前面的经验,它的使用方法应该是a<

我再写一个,方便理解友函数有什么用

std::ostream& operator<<( const Complexs& c) {
    std::ostream& os=std::cout << c.real << " + " << c.imag << "i";
    return os;
}

首先,使用方法依然是a<

friend std::ostream& operator<<(std::ostream& os, const Complexs& c) {
        os << c.real << " + " << c.imag << "i";
        return os;
    }

除此之外,friend还能让在class外声明的函数能够访问private和protected

class Complex {
private:
    double real;
    double imag;

public:
    Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {}

    // 声明友元函数,允许 operator<< 访问私有成员
    friend std::ostream& operator<<(std::ostream& os, const Complex& c);
};

// 定义友元函数(非成员函数)
std::ostream& operator<<(std::ostream& os, const Complex& c) {
    os << c.real << " + " << c.imag << "i"; // 可以访问私有成员 real 和 imag
    return os;
}

这里没有friend是无法访问c.real的

你可能感兴趣的:(学习,笔记,c++)