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<<b,相当于a.operator(b),b是std::ostream& os型,a应该有成员real,imag,所以是Complex a;a<<std::cout,整个返回值是std::cout<<a.real<<"+"<<a.imag<<"i",能实现输出2+3i的虚数效果,但是这个很反常规,所以要改写。
我再写一个,方便理解友函数有什么用
std::ostream& operator<<( const Complexs& c) {std::ostream& os=std::cout << c.real << " + " << c.imag << "i";return os;
}
首先,使用方法依然是a<<b,刚知道因为operator在Complex类中,它的左操作数就必须是这个类的,右操作数b显然也是这个类,这里a并未使用,依然可以运行,但是只能让os=cout,我们想进行其他操作就必须改变顺序,做到os<<Complexhans,这就需要friend改变传参顺序了。
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 和 imagreturn os;
}
这里没有friend是无法访问c.real的