10. C++操作符重载

在介绍C++中操作符重载之前,先介绍下C++标准库。

一、C++标准库

         1. C++标准库并不是C++语言的一部分;
                2. C++标准库是由C++语言编写而成的类库和函数的集合;
                3. C++标准库中定义的类和对象都位于std命名空间中;
                4. C++标准库的头文件都不带.h后缀;
                5. C++标准库涵盖了C库的功能;
                           C库中<name.h>头文件对应C++中的<cname>;

C++标准库预定义了多数常用的数据结构,如:字符串,链表,队列,栈等。<bitset>  <deque>  <list>  <map>  <queue>  <set>  <stack>  <vector>

#include <cstdio>

using namespace std;

int main()
{
	printf("Hello World!\n");

	printf("Press any key to continue...");

	getchar();

	return 0;
}

#include <iostream>

using namespace std;

int main()
{
	cout<<"Hello World"<<endl;
    
	int x;
	int y;

	cout<<"1st Parameter: ";
	cin>>x;

	cout<<"2nd Parameter: ";
	cin>>y;

	cout<<"Result: "<<x+y<<endl;

	return 0;
}

左移运算符 << 和 右移运算符 >> 在C语言中只能用于整数运算,并且语义是确定不变的。C++是怎么改变左移运算符和右移运算符的语义的?

 

二、操作符重载

操作符重载为操作符提供不同的语义。

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;
    int b;
};

int main(int argc, char *argv[])
{
    Complex c1 = {1, 2};
    Complex c2 = {3, 4};
    Complex c3 = c1 + c2;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

很显然,编译出错了,不管是C还是C++中,“+”符号只能用于整数和浮点数的相加。这里是两个结构体相加,那肯定要报错了。那该怎么解决这个问题呢?

可以定义一个add函数用于两个Complex的相加。

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;
    int b;
};

Complex add(const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1 = {1, 2};
    Complex c2 = {3, 4};
    Complex c3 = add(c1, c2);
    
    cout<<"c3.a = "<<c3.a<<endl;
    cout<<"c3.b = "<<c3.b<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

add函数可以解决Complex变量相加的问题,但是Complex是现实世界中确实存在的复数,并且复数在数学中的地位和普通的实数相同。为什么不能让 + 操作符也支持复数相加呢?

 

C++中操作符重载的本质
               1. C++中通过operator关键字可以利用函数扩展操作符;
               2. operator的本质是通过函数重载实现操作符重载;

#include <cstdlib>
#include <iostream>

using namespace std;

struct Complex
{
    int a;
    int b;
};

Complex operator+(const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1 = {1, 2};
    Complex c2 = {3, 4};
    Complex c3 = c1 + c2;
    //Complex c3 = operator+(c1, c2);
	
    cout<<"c3.a = "<<c3.a<<endl;
    cout<<"c3.b = "<<c3.b<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

用operator关键字扩展的操作符可以用于类吗?

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
};

Complex operator+ (const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

该怎么进行改进呢?

C++中的类的友元

        private声明使得类的成员不能被外界访问。但是通过friend关键字可以例外的开放权限。

 

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    friend Complex operator+ (const Complex& c1, const Complex& c2);
};

Complex operator+ (const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

 编译运行结果如下:

 

左移操作符的重载 

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    friend Complex operator+ (const Complex& c1, const Complex& c2);
    friend ostream& operator<< (ostream& out, const Complex& c);
};

ostream& operator<< (ostream& out, const Complex& c)
{
    out<<c.a<<" + "<<c.b<<"i";
    
    return out;
}

Complex operator+ (const Complex& c1, const Complex& c2)
{
    Complex ret;
    
    ret.a = c1.a + c2.a;
    ret.b = c1.b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2;
    
    cout<<c1<<endl;
    cout<<c2<<endl;
    cout<<c3<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译结果如下:

关于ostream的详细用法可以参考https://blog.csdn.net/luoyayun361/article/details/87972929

小结:

        1. 操作符重载是C++的强大特性之一
                2. 操作符重载的本质是通过函数扩展操作符的语义
                3. operator关键字是操作符重载的关键
                4. friend关键字可以对函数或类开发访问权限
                5. 操作符重载遵循函数重载的规则

 

 

通过operator关键字能够将操作符定义为全局函数。操作符重载的本质就是函数重载。类的成员函数是否可以作为操作符重载的函数?

operator+的成员函数实现

用成员函数重载的操作符,比全局操作符重载函数少一个参数,即左操作数。不需要使用friend关键字。

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
    int a;
    int b;
public:
    Complex(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    Complex operator+ (const Complex& c2);
    
    friend ostream& operator<< (ostream& out, const Complex& c);
};

ostream& operator<< (ostream& out, const Complex& c)
{
    out<<c.a<<" + "<<c.b<<"i";
    
    return out;
}

Complex Complex::operator+ (const Complex& c2)
{
    Complex ret(0, 0);
    
    ret.a = this->a + c2.a;
    ret.b = this->b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2;
    
    cout<<c1<<endl;
    cout<<c2<<endl;
    cout<<c3<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

什么时候使用全局函数重载操作符?什么时候使用成员函数重载操作符?

当无法修改左操作数的类时,使用全局函数进行重载。=, [], ()和->操作符只能通过成员函数进行重载。
 

数组类的改进

       重载赋值操作符,重载数组操作符,重载比较操作符

//Array.cpp
#include <stdio.h>
#include "Array.h"

Array::Array(int length)
{
    if( length < 0 )
    {
        length = 0;
    }
    
    mLength = length;
    mSpace = new int[mLength];
}

Array::Array(const Array& obj)
{
    mLength = obj.mLength;
    
    mSpace = new int[mLength];
    
    for(int i=0; i<mLength; i++)
    {
        mSpace[i] = obj.mSpace[i];
    }
}

int Array::length()
{
    return mLength;
}

Array::~Array()
{
    mLength = -1;
    printf("%08X\n", mSpace);
    delete[] mSpace;
}

int& Array::operator[](int i)
{
    return mSpace[i];
}

Array& Array::operator= (const Array& obj)
{
    delete[] mSpace;
    
    mLength = obj.mLength;
    
    mSpace = new int[mLength];
    
    for(int i=0; i<mLength; i++)
    {
        mSpace[i] = obj.mSpace[i];
    }
    
    return *this;
}

bool Array::operator== (const Array& obj)
{
    bool ret = true;
    
    if( mLength == obj.mLength )
    {
        for(int i=0; i<mLength; i++)
        {
            if( mSpace[i] != obj.mSpace[i] )
            {
                ret = false;
                break;
            }
        }
    }
    else
    {
        ret = false;
    }
    
    return ret;
}

bool Array::operator!= (const Array& obj)
{
    return !(*this == obj);
}
//Array.h
#ifndef _ARRAY_H_
#define _ARRAY_H_

class Array
{
private:
    int mLength;
    int* mSpace;

public:
    Array(int length);
    Array(const Array& obj);
    int length();
    ~Array();
    int& operator[](int i);
    Array& operator= (const Array& obj);
    bool operator== (const Array& obj);
    bool operator!= (const Array& obj);
};

#endif
//main.cpp
#include <stdio.h>
#include "Array.h"

int main()
{
    Array a1(10);
    Array a2(0);
    Array a3(0);
    
    if( a1 != a2 )
    {
        printf("a1 != a2\n");
    }
    
    for(int i=0; i<a1.length(); i++)
    {
        a1[i] = i + 1;
    }
    
    for(int i=0; i<a1.length(); i++)
    {
        printf("Element %d: %d\n", i, a1[i]);
    }
    
    a3 = a2 = a1;
    
    if( a1 == a2 )
    {
        printf("a1 == a2\n");
    }
    
    for(int i=0; i<a2.length(); i++)
    {
        printf("Element %d: %d\n", i, a2[i]);
    }
    
    printf("Press any key to continue...");
    getchar();
    return 0;
}

编译运行结果如下:

C++编译器会为每个类提供默认的赋值操作符。默认的赋值操作符只是做简单的值复制。类中存在指针成员变量时就需要重载赋值操作符。

 

++操作符的重载

        ++操作符只有一个操作数,++操作符有前缀和有后缀的区分。如何重载++操作符才能区分前置运算和后置运算?

注:C++中通过一个占位参数来区分前置运算和后置运算。

#include <cstdlib>
#include <iostream>

using namespace std;

class Complex
{
    int a;
    int b;
public:
    Complex(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    Complex operator+ (const Complex& c2);
    Complex operator++ (int);
    Complex& operator++();
    
    friend ostream& operator<< (ostream& out, const Complex& c);
};

ostream& operator<< (ostream& out, const Complex& c)
{
    out<<c.a<<" + "<<c.b<<"i";
    
    return out;
}

Complex Complex::operator++ (int)
{
    Complex ret = *this;
    
    a++;
    b++;
    
    return ret;
    
}

Complex& Complex::operator++()
{
    ++a;
    ++b;
    
    return *this;
}

Complex Complex::operator+ (const Complex& c2)
{
    Complex ret(0, 0);
    
    ret.a = this->a + c2.a;
    ret.b = this->b + c2.b;
    
    return ret;
}

int main(int argc, char *argv[])
{
    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c2;
    
    c2++;
    ++c3;
    
    cout<<c1<<endl;
    cout<<c2<<endl;
    cout<<c3<<endl;
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

 

不要重载&&和||操作符,为什么?

#include <cstdlib>
#include <iostream>

using namespace std;

class Test
{
    int i;
public:
    Test(int i)
    {
        this->i = i;
    }
    
    Test operator+ (const Test& obj)
    {
        Test ret(0);
        
        cout<<"Test operator+ (const Test& obj)"<<endl;
        
        ret.i = i + obj.i;
        
        return ret;
    }
    
    bool operator&& (const Test& obj)
    {
        cout<<"bool operator&& (const Test& obj)"<<endl;
        
        return i && obj.i;
    }
};

int main(int argc, char *argv[])
{
    int a1 = 0;
    int a2 = 1;
    
    if( a1 && (a1 + a2) )
    {
        cout<<"Hello"<<endl;
    }
    
    Test t1 = 0;
    Test t2 = 1;
    
    if( t1 && (t1 + t2) )
    {
        cout<<"World"<<endl;
    }
    
    cout << "Press the enter key to continue ...";
    cin.get();
    return EXIT_SUCCESS;
}

编译运行结果如下:

&&和||是C++中非常特殊的操作符。&&和||内置实现了短路规则,操作符重载是靠函数重载来完成的,操作数作为函数参数传递,C++的函数参数都会被求值,无法实现短路规则。
 

小结

       1. 操作符重载可以直接使用类的成员函数实现;

       2. =, [], ()和->操作符只能通过成员函数进行重载;

       3. ++操作符通过一个int参数进行前置与后置的重载;

       4. C++中不要重载&&和||操作符;
 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章