C++基础——友元类和友元的关系性质
程序员文章站
2022-06-02 22:07:00
五十九. 友元类和友元的关系性质
#include
using namespace std;
class A
{
public:
A(int a)...
五十九. 友元类和友元的关系性质
#include using namespace std; class A { public: A(int a){ this->a = a; } void printA(){ cout<<"a= "<a<b =b; } void printB(){ A objA(100); cout<b<友元和友类的重要关系性质
六十. 操作符重载的基本语法
#include using namespace std; class Complex { public: Complex(int a,int b) { this->a = a; this->b = b; } void printComplex() { cout<<"("<a<<","<b<<"i)"<a+ another.a, this->b+another.b); return temp; } Complex operator+ (Complex &another) //注意operator与后面的操作符,必须中间没有空格,视operator为一个函数 { Complex temp(this->a+ another.a, this->b+another.b); return temp; } private: int a; int b; }; #if 0 Complex complexAdd(Complex &c1,Complex &c2) { Complex temp(c1.a+c2.a,c1.b+c2.b); return temp; } #endif #if 0 //操作符重载写在全局 Complex operator+ (Complex &c1, Complex &c2) //注意operator与后面的操作符,必须中间没有空格,视operator为一个函数 { Complex temp(c1.a+ c2.a, c1.b+c2.b); return temp; } #endif int main() { Complex c1(1,2); Complex c2(2,4); c1.printComplex(); c2.printComplex(); //Complex c3=complexAdd(c1,c2); //Complex c3= c1+c2; //操作符重载写在全局,调用方法1 //Complex c3 = operator+(c1,c2); //操作符重载写在全局,调用方法2 //Complex c3= c1+c2; //操作符重载写在类中,调用方法1 Complex c3= c1.operator+(c2); //操作符重载写在类中,调用方法2 c3.printComplex(); return 0; };>;>;>;>
下一篇: C++ 仿函数代码实例