(八)C++类和对象之运算符重载

4 类和对象


4.5 运算符重载


​ 运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。

4.5.1 加号运算符重载


​ 作用:实现两个自定义数据类型相加的运算。

例4.5.1

#include <iostream>

using namespace std;

class Person
{
    
    
public:
	Person() {
    
    };
	Person(int a, int b)
	{
    
    
		this->m_A = a;
		this->m_B = b;
	}
	//成员函数实现 + 号运算符重载
	Person operator+(const Person& p) 
	{
    
    
		Person temp;
		temp.m_A = this->m_A + p.m_A;
		temp.m_B = this->m_B + p.m_B;
		return temp;
	}


public:
	int m_A;
	int m_B;
};

//全局函数实现 + 号运算符重载
//Person operator+(const Person& p1, const Person& p2) 
//{
    
    
//	Person temp(0, 0);
//	temp.m_A = p1.m_A + p2.m_A;
//	temp.m_B = p1.m_B + p2.m_B;
//	return temp;
//}

//运算符重载 可以发生函数重载 
Person operator+(const Person& p2, int val)  
{
    
    
	Person temp;
	temp.m_A = p2.m_A + val;
	temp.m_B = p2.m_B + val;
	return temp;
}

void test() 
{
    
    

	Person p1(10, 10);
	Person p2(20, 20);

	//成员函数方式
	Person p3 = p2 + p1;  //相当于 p2.operaor+(p1)
	cout << "mA:" << p3.m_A << " mB:" << p3.m_B << endl;


	Person p4 = p3 + 10; //相当于 operator+(p3,10)
	cout << "mA:" << p4.m_A << " mB:" << p4.m_B << endl;

}

int main() 
{
    
    
	test();

	return 0;
}

​ 结果如下:

mA:30 mB:30
mA:40 mB:40

Process returned 0 (0x0)   execution time : 0.179 s
Press any key to continue.
  • 对于内置的数据类型的表达式的的运算符是不可能改变的。

  • 不要滥用运算符重载。

4.5.2 左移运算符重载


​ 作用:重载左移运算符配合友元可以实现输出自定义数据类型。

例4.5.2

#include <iostream>

using namespace std;

class Person
{
    
    
	friend ostream& operator<<(ostream& out, Person& p);

public:

	Person(int a, int b)
	{
    
    
		this->m_A = a;
		this->m_B = b;
	}

	//成员函数 实现不了  p << cout 不是我们想要的效果
	//void operator<<(Person& p)
	//{
    
    
	//
	//}

private:
	int m_A;
	int m_B;
};

//全局函数实现左移重载
//ostream对象只能有一个
ostream& operator<<(ostream& out, Person& p)
{
    
    
	out << "a:" << p.m_A << " b:" << p.m_B;
	return out;
}

void test()
{
    
    

	Person p1(10, 20);

	cout << p1 << '\n' << "hello world" << endl; //链式编程
}

int main()
{
    
    
	test();

	return 0;
}

​ 结果如下:

a:10 b:20
hello world

Process returned 0 (0x0)   execution time : 0.007 s
Press any key to continue.

4.5.3 递增运算符重载


作用

  • 通过重载递增运算符,实现自己的整型数据。
  • 前置递增返回引用,后置递增返回值。

例4.5.3

#include <iostream>

using namespace std;

class MyInteger
{
    
    

	friend ostream& operator<<(ostream& out, MyInteger myint);

public:
	MyInteger()
	{
    
    
		m_Num = 0;
	}
	//前置++
	MyInteger& operator++()
	{
    
    
		//先++
		m_Num++;
		//再返回
		return *this;
	}

	//后置++
	MyInteger operator++(int)
	{
    
    
		//先返回
		MyInteger temp = *this; //记录当前本身的值,然后让本身的值加1,但是返回的是以前的值,达到先返回后++;
		m_Num++;
		return temp;
	}

private:
	int m_Num;
};


ostream& operator<<(ostream& out, MyInteger myint)
{
    
    
	out << myint.m_Num;
	return out;
}


//前置++ 先++ 再返回
void test01()
{
    
    
	MyInteger myInt;
	cout << ++myInt << endl;
	cout << myInt << endl;
}

//后置++ 先返回 再++
void test02()
{
    
    

	MyInteger myInt;
	cout << myInt++ << endl;
	cout << myInt << endl;
}

int main()
{
    
    

	test01();
	test02();

	return 0;
}

​ 结果如下:

1
1
0
1

Process returned 0 (0x0)   execution time : 0.007 s
Press any key to continue.

4.5.4 赋值运算符重载


​ c++编译器至少给一个类添加4个函数

  1. 默认构造函数(无参,函数体为空)
  2. 默认析构函数(无参,函数体为空)
  3. 默认拷贝构造函数,对属性进行值拷贝
  4. 赋值运算符 operator=, 对属性进行值拷贝

​ 如果类中有属性指向堆区,做赋值操作时也会出现深浅拷贝问题。

例4.5.4

#include <iostream>

using namespace std;

class Person
{
    
    
public:

	Person(int age)
	{
    
    
		//将年龄数据开辟到堆区
		m_Age = new int(age);
	}

	//重载赋值运算符
	Person& operator=(Person &p)
	{
    
    
		if (m_Age != NULL)
		{
    
    
			delete m_Age;
			m_Age = NULL;
		}
		//编译器提供的代码是浅拷贝
		//m_Age = p.m_Age;

		//提供深拷贝 解决浅拷贝的问题
		m_Age = new int(*p.m_Age);

		//返回自身
		return *this;
	}


	~Person()
	{
    
    
		if (m_Age != NULL)
		{
    
    
			delete m_Age;
			m_Age = NULL;
		}
	}

	//年龄的指针
	int *m_Age;

};


void test01()
{
    
    
	Person p1(18);

	Person p2(20);

	Person p3(30);

	p3 = p2 = p1; //赋值操作

	cout << "p1的年龄为:" << *p1.m_Age << endl;

	cout << "p2的年龄为:" << *p2.m_Age << endl;

	cout << "p3的年龄为:" << *p3.m_Age << endl;
}

int main()
{
    
    

	test01();

	//int a = 10;
	//int b = 20;
	//int c = 30;

	//c = b = a;
	//cout << "a = " << a << endl;
	//cout << "b = " << b << endl;
	//cout << "c = " << c << endl;

	return 0;
}

​ 结果如下:

p1的年龄为:18
p2的年龄为:18
p3的年龄为:18

Process returned 0 (0x0)   execution time : 0.109 s
Press any key to continue.

4.5.5 关系运算符重载


作用: 重载关系运算符,可以让两个自定义类型对象进行对比操作。

例4.5.5

#include <iostream>

using namespace std;

class Person
{
    
    
public:
	Person(string name, int age)
	{
    
    
		this->m_Name = name;
		this->m_Age = age;
	};

	bool operator==(Person & p)
	{
    
    
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
    
    
			return true;
		}
		else
		{
    
    
			return false;
		}
	}

	bool operator!=(Person & p)
	{
    
    
		if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
    
    
			return false;
		}
		else
		{
    
    
			return true;
		}
	}

	string m_Name;
	int m_Age;
};

void test01()
{
    
    
	//int a = 0;
	//int b = 0;

	Person a("孙悟空", 18);
	Person b("孙悟空", 20);

	if (a == b)
	{
    
    
		cout << "a和b相等" << endl;
	}
	else
	{
    
    
		cout << "a和b不相等" << endl;
	}

	/*if (a != b)
	{
		cout << "a和b不相等" << endl;
	}
	else
	{
		cout << "a和b相等" << endl;
	}*/
}


int main()
{
    
    

	test01();

	return 0;
}

例4.5.5

a和b不相等

Process returned 0 (0x0)   execution time : 0.060 s
Press any key to continue.

4.5.6 函数调用运算符重载


  • 函数调用运算符 () 也可以重载。
  • 由于重载后使用的方式非常像函数的调用,因此称为仿函数。
  • 仿函数没有固定写法,非常灵活。

例4.5.6

#include <iostream>

using namespace std;

class MyPrint
{
    
    
public:
	void operator()(string text)
	{
    
    
		cout << text << endl;
	}

};

void test01()
{
    
    
	//重载的()操作符 也称为仿函数
	MyPrint myFunc;
	myFunc("hello world");
}


class MyAdd
{
    
    
public:
	int operator()(int v1, int v2)
	{
    
    
		return v1 + v2;
	}
};

void test02()
{
    
    
	MyAdd add;
	int ret = add(10, 10);
	cout << "ret = " << ret << endl;

	//匿名对象调用
	cout << "MyAdd()(100,100) = " << MyAdd()(100, 100) << endl;
}

int main()
{
    
    
	test01();
	test02();

	return 0;
}

​ 结果如下:

hello world
ret = 20
MyAdd()(100,100) = 200

Process returned 0 (0x0)   execution time : 0.052 s
Press any key to continue.

4.5.7 重载+, - ,*, /, >>,<<运算符


​ 题目如下:

​ 上机实验四设计一个 Complex 类,并在 Complex 中重载+, - ,*, /, >>以及<<等运算符。

  1. 建构数个 Complex 物件,测试对象的所有成员函数(member functions)。
  2. 建构数个 Complex 物件的指针(pointer),以指针测试物件的所有成员函数(member functions)。

Complex

-Real : double
-Imaginary : double
<<constructor>> +Complex(real : double = 0.0,
imaginary : double = 0.0)
<<desctructor>> +~Complex()
+setReal(real : double)
+getReal() : double
+setImaginary(imaginary : double)
+getImaginary() : double
+operator+(c: Complex) : Complex &
+operator-(c: Complex) : Complex &
+operator*(c: Complex) : Complex &
+operator/(c: Complex) : Complex &
<<friend>>+operator>>(input : istream&, c :
&Complex) : istream&
<<friend>>+operator<<(output : ostream&, c :
Complex) : ostream&

​ 解答如下:

​ main.cpp

#include <iostream>
#include "Complex.h"
using namespace std;

int main()
{
    
    
    Complex c1(3.0, 4.0);
    Complex c2(4.0, 5.0);
    Complex c3;
    Complex c4;
    Complex c5;
    Complex c6;

    c3 = c1 + c2;
    c4 = c1 - c2;
    c5 = c1 * c2;
    c6 = c1 / c2;

    cout << "c1 = " << c1 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c1 + c2 = " << c3 << endl;
    cout << "c1 - c2 = " << c4 << endl;
    cout << "c1 * c2 = " << c5 << endl;
    cout << "c1 / c2 = " << c6 << endl;

    Complex *ptr1;
    Complex *ptr2;
    Complex *ptr3;
    Complex *ptr4;
    Complex *ptr5;
    Complex *ptr6;

    ptr1 = new Complex(7.0, 8.0);
    ptr2 = new Complex(6.0, 5.0);
    ptr3 = new Complex();
    ptr4 = new Complex();
    ptr5 = new Complex();
    ptr6 = new Complex();

    *ptr3 = *ptr1 + *ptr2;
    *ptr4 = *ptr1 - *ptr2;
    *ptr5 = *ptr1 * *ptr2;
    *ptr6 = *ptr1 / *ptr2;

    cout << "*ptr1 = " << *ptr1 << endl;
    cout << "*ptr2 = " << *ptr2 << endl;
    cout << "*ptr1 + *ptr2 = " << *ptr3 << endl;
    cout << "*ptr1 - *ptr2 = " << *ptr4 << endl;
    cout << "*ptr1 * *ptr2 = " << *ptr5 << endl;
    cout << "*ptr1 / *ptr2 = " << *ptr6 << endl;

    delete ptr3;
    delete ptr4;
    delete ptr5;
    delete ptr6;

    return 0;
}

​ Complex.h

#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

using namespace std;

class Complex
{
    
    
public:
    Complex();
    Complex(double real, double imaginary); // default constructor
    ~Complex();

    void setReal(double real);
    void setImaginary(double imaginary);

    double getReal();
    double getImaginary();

    Complex operator+(const Complex& c); // 重载
    Complex operator-(const Complex& c); //
    Complex operator*(const Complex& c); //
    Complex operator/(const Complex& c); //

    friend istream& operator>>(istream& input, Complex& a);
    friend ostream& operator<<(ostream& output, Complex& a);

    void print(); // in real + i imaginary
private:
    double Real;
    double Imaginary;
};
#endif // COMPLEX_H

​ Complex.cpp

#include "Complex.h"

using namespace std;

Complex::Complex()
{
    
    
    Real = 0.0;
    Imaginary = 0.0;
}

Complex::Complex(double real, double imaginary)
{
    
    
    setReal(real);
    setImaginary(imaginary);
}

Complex::~Complex()
{
    
    
    //cout << "object Destructor is called" << endl;
}

void Complex::setReal(double real)
{
    
    
    Real = real;
}

void Complex::setImaginary(double imaginary)
{
    
    
    Imaginary = imaginary;
}

double Complex::getReal()
{
    
    
    return Real;
}

double Complex::getImaginary()
{
    
    
    return Imaginary;
}

Complex Complex::operator+(const Complex& c)
{
    
    
    return Complex(getReal() + c.Real, getImaginary() + c.Imaginary);
}

Complex Complex::operator-(const Complex& c)
{
    
    
    return Complex(getReal() - c.Real, getImaginary() - c.Imaginary);
}

Complex Complex::operator*(const Complex& c)
{
    
    
    return Complex(getReal() * c.Real - getImaginary() * c.Imaginary, getReal() * c.Imaginary + getImaginary() * c.Real);
}

Complex Complex::operator/(const Complex& c)
{
    
    
    double denominator = c.Real * c.Real + c.Imaginary * c.Imaginary;
    double a = getReal() * c.Real + getImaginary() * c.Imaginary;
    double b = getImaginary() * c.Real - getReal() * c.Imaginary;
    return Complex(a / denominator, b / denominator);
}

// 重载输入运算符
istream& operator>>(istream& input, Complex& c)
{
    
    
    input >> c.Real >> c.Imaginary;
    return input;
}

// 重载输出运算符
ostream& operator<<(ostream& output, Complex& c)
{
    
    
    output << c.getReal() << "+" << c.getImaginary() << "i";
    return output;
}

void Complex::print()
{
    
    
    cout << "Real is " << getReal() << endl;
    cout << "Imaginary is " << getImaginary() << endl;
    cout << endl;
}

​ 结果如下:

c1 = 3+4i
c2 = 4+5i
c1 + c2 = 7+9i
c1 - c2 = -1+-1i
c1 * c2 = -8+31i
c1 / c2 = 0.780488+0.0243902i
*ptr1 = 7+8i
*ptr2 = 6+5i
*ptr1 + *ptr2 = 13+13i
*ptr1 - *ptr2 = 1+3i
*ptr1 * *ptr2 = 2+83i
*ptr1 / *ptr2 = 1.34426+0.213115i

Process returned 0 (0x0)   execution time : 0.070 s
Press any key to continue.

猜你喜欢

转载自blog.csdn.net/2301_80391227/article/details/143153207