运算符重载

浅浅的花香味﹌ 2022-04-10 07:23 364阅读 0赞

运算符重载函数作为成员函数

  1. class Complex {
  2. public:
  3. Complex() {
  4. real = 0.0, imag = 0.0;
  5. }
  6. Complex(double real, double imag) {
  7. this->real = real;
  8. this->imag = imag;
  9. }
  10. Complex operator+ (Complex &c2);
  11. void display();
  12. private:
  13. double real,imag;
  14. };
  15. //运算符重载函数定义:
  16. Complex Complex::operator+(Complex &c2) {
  17. Complex c;
  18. c.real = real + c2.real;
  19. c.imag = imag + c2.imag;
  20. return c;
  21. //return(Complex(real+c2.real,imag+c2.imag));//这样比较简便
  22. }
  23. void Complex::display() {
  24. cout << real << "+" << imag << "i" << endl;
  25. }
  26. int main() {
  27. Complex c1(3, 1);
  28. Complex c2(4, 4);
  29. Complex c = c1 + c2;
  30. c.display();
  31. system("pause");
  32. }

解读

1 运算符的重载实质上函数的重载。
c1 + c2相当于c1.operator+(c2),这里operator+是一个函数名。

不允许重载的运算符




















成员访问运算符 成员指针访问运算符 域运算符 长度运算符 条件运算符
. * :: sizeof ?:

运算符重载函数作为友元类函数(效果与上面相同)

  1. class Complex {
  2. public:
  3. Complex() {
  4. real = 0.0, imag = 0.0;
  5. }
  6. Complex(double real, double imag) {
  7. this->real = real;
  8. this->imag = imag;
  9. }
  10. friend Complex operator+ (Complex &c1, Complex &c2);
  11. void display();
  12. private:
  13. double real,imag;
  14. };
  15. void Complex::display() {
  16. cout << real << "+" << imag << "i" << endl;
  17. }
  18. Complex operator+ (Complex &c1, Complex &c2) {
  19. return Complex(c1.real + c2.real, c1.imag + c2.imag);
  20. }
  21. int main() {
  22. Complex c1(3, 1);
  23. Complex c2(4, 4);
  24. Complex c = c1 + c2;
  25. c.display();
  26. system("pause");
  27. }

c1+c2相当于operator+(c1,c2)。

总结

如果作为成员函数,他可以通过this指针自由地访问本类的数据成员,因此可以少些一个函数的参数。作为友元函数,则函数的参数列表中必须有两个参数,不能省略

发表评论

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

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

相关阅读

    相关 运算符重载

    不能重载的运算符有:. 和 :: 和 ?:和.\和sizeof 注意点1: 使用运算符重载的本质上是一次函数调用,所以这些关于运算对象的求值顺序无法应用到重载的运算符上。

    相关 运算符重载

    一、运算符重载。 什么是运算符重载? 运算符重载:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。 二、加号运算符重载。 作用: 实现两个自定

    相关 运算符重载

    实现函数运算符的实质:编写一个函数,该函数以“operator运算符号”为函数名,其定义了重载的运算符将要执行的操作。(给自己的类进行运算) 运算符重载有两种形式:重载为类的

    相关 运算符重载

    c++的一大特性就是重载(overload),通过重载可以把功能相似的几个函数合为一个,使得程序更加简洁、高效。在c++中不止函数可以重载,运算符也可以重载。由于一般数据类型间