c++操作符重载实现

逃离我推掉我的手 2022-06-16 11:26 290阅读 0赞

为什么要用操作符重载

首先我们看一个例子。

class Complex

{

public:

int a;

int b;

public:

Complex(int a = 0,int b=0)

{

this->a = a;

this->b = b;

}

void print()

{

cout << “a:” << a << endl;

cout << “b:” << b << endl;

}

};

void main01()

{

Complex c1(1, 2), c2(3, 4);

int a = 10, b = 20;

a = a + b;// int 是基础类新,编译器已经为这些类型提供+操作了。

//c1 = c1 + c2;// c1的类型是complex,这种类型是自定义类型,编译器根本不知道如何加。

}

通过这个例子我们知道对于自定义数据类型,编译器根本不知道如何解析操作符。但是c++编译器会给你提供一种机制,让你实现自定义类型加。这就引入了操作符重载的概念。

C++允许用户通过自定义的方式实现操作符重载。

操作符重载初探:

class Complex

{

public:

int a;

int b;

public:

Complex(int a = 0,int b=0)

{

this->a = a;

this->b = b;

}

void print()

{

cout << “a:” << a << endl;

cout << “b:” << b << endl;

}

};

Complex add(Complex& c1,Complex& c2)

{

Complex tmp;

tmp.a = c1.a + c2.a;

tmp.b = c1.b + c2.b;

return tmp;

}

// 操作符重载首先是通过函数实现的。记住operator+是函数名。

Complex operator+(Complex& c1, Complex& c2)

{

Complex tmp;

tmp.a = c1.a + c2.a;

tmp.b = c1.b + c2.b;

return tmp;

}

void main()

{

Complex c1(1, 2), c2(3, 4);

// Complex c3 = add(c1, c2);

// Complex c3 = operator+(c1, c2);

Complex c3 = c1 + c2;

c3.print();

}

上面的例子我们发现add(c1, c2); operator+(c1, c2); c1 + c2是等价的,换句话说,重载的操作符本质上是一个函数名。

C++操作符重载有两种方式实现:友元函数,成员函数。

1 友元函数实现操作符重载

class Complex

{

private:

int a;

int b;

friend Complex operator+(Complex &c1, Complex& c2);

friend Complex& operator++(Complex &c2);

public:

Complex(int a = 0, int b = 0)

{

this->a = a;

this->b = b;

}

void print()

{

cout << “a:” << a << endl;

cout << “b:” << b << endl;

}

};

// 操作符重载首先是通过函数实现的。operator+是函数名。

Complex operator+(Complex &c1, Complex& c2)

{

Complex tmp;

tmp.a = c1.a + c2.a;

tmp.b = c1.b + c2.b;

return tmp;

}

// 实现前置++;operator++是函数名。

Complex& operator++(Complex &c2)

{

c2.a++;

c2.b++;

return c2;

}

void main()

{

Complex c1(1, 2), c2(3, 4);

Complex c3 = c1 + c2; //等价于:Complex c3 = operator+(c1, c2);

c3.print();

Complex c4(5, 6);

++c4; //等价于: operator++(c4);

c4.print();

}

注释:

c++中不能用友元函数重载的运算符有:= () [ ] ->

2 成员函数实现操作符重载

class Complex

{

private:

int a;

int b;

public:

Complex(int a = 0, int b = 0)

{

this->a = a;

this->b = b;

}

void print()

{

cout << “a:” << a << endl;

cout << “b:” << b << endl;

}

// 操作符重载首先是通过函数实现的。operator+是函数名。

Complex& operator+(Complex& c2)

{

a = a + c2.a;

b = b + c2.b;

return *this;

}

Complex& operator++()

{

this->a++;

this->b++;

return *this;

}

};

void main()

{

Complex c1(1, 2), c2(3, 4);

Complex c3 = c1 + c2;//相当于Complex c3 = c1.operator+(c2);

c3.print();

Complex c4(5, 6);

++c4;//相当于 c4.operator++();

c4.print();

}

发表评论

表情:
评论列表 (有 0 条评论,290人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++操作符重载

    又看了一遍操作符的东西,感觉之前对操作符的理解还停留在很浅的认知上(仅仅会用哈哈),所以做一下笔记来加深一下印象。 文章目录 一、为什么会有操作符重载

    相关 C++中操作符重载

    一、操作符重载属于什么? 在本文开始阐述之前,首先明确,操作符重载是一个具有特殊名的“ 函数 ”。 既然作为函数,那么,就具有函数的特性,一是形参表,二是返回值。 关键字