zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ Primer注意事项11_运算符重载_算术/关系运算符_下标运算符

C++ 11 关系 运算符 注意事项 重载 primer 下标
2023-09-14 09:10:15 时间

1.算术/关系运算符

        平时,定义成非成员函数以同意左右側运算对象进行转换。由于这些运算符一般不须要改变运算对象的状态,所以形參都是常量的引用。


以"+"号运算符为例:

Person operator+(const Person &p1, const Person &p2)
{
	string s1(*p1.name);
	string s2(*p2.name);
	Person p;
	p.age = p1.age + p2.age;
	p.name = new string(s1+s2);
	return p;
}
int main()
{
	Person p1(20, "SCOTT");
	Person p2(10, "Kate");
	Person p3;
	p3 = p1 + p2;
	cout << p3 << endl;

	return 0;
}

上面的函数应该定义为友元函数,由于直接用到了成员变量。

执行结果:

Init Person
Init Person
Default Person
Default Person
operator =
~Person name: 0x9087058 age: 30
p.age: 30, p.name: SCOTTKate
~Person name: 0x9087088 age: 30
~Person name: 0x9087048 age: 10
~Person name: 0x9087020 age: 20

能够看出,我们这里的+号操作,成功的讲两个人的年龄与姓名相加,最然这没有什么实际意义,但这里重在演示。对应的异常处理为节省时间也没加。


2.关系运算符

这里以==关系运算符为例:

bool operator==(const Person &p1, const Person &p2)
{
	if(p1.age == p2.age && p1.name == p2.name)
	{
		return true;
	}
	return false;
}

int main()
{
	Person p1(20, "SCOTT");
	Person p2(10, "Kate");
	Person p3;
	if(p1 == p2)
	{
		cout << "p1 == p2" << endl;
	}
	else
	{
		cout << "p1 != p2" << endl;
	}

	return 0;
}

为了方便。直接推断的name,name是一个指针。按理说应该是*name 但这样就要加异常处理,也是为了节省时间。
执行结果:

Init Person
Init Person
Default Person
p1 != p2
~Person name: 0 age: 0
~Person name: 0x84fc048 age: 10
~Person name: 0x84fc020 age: 20


3.下标运算符

能够从容器中检索单个元素的容器类通常会定义下标操作符,即operator[]。如vectorstring

下标操作符必须定义为类成员函数。

类定义下标操作符时。一般须要定义两个版本号:一个为非const成员并返回引用,还有一个为const成员并返回引用。

给出一个简单的样例:

#include <iostream>
#include <new>
using namespace std;

class Array 
{
public:
   Array(int size) : _size(size) 
   { 
	_val = new int[_size];
   }
   int& operator[] (int index) 
   { 
	return _val[index];
   }

   const int& operator[] (int index) const 
   { 
	return _val[index]; 
   }
private:    
   int _size;
   int *_val;
};

int main()
{
	Array a1(10);
	for(int i = 0; i<10; i++)
	{
		a1[i] = i;
		cout << a1[i] << endl;
	}
	const Array a2(100);
	for(int i = 0; i<100; i++)
	{
//		a2[i] = i;   error  read-only!!!
		cout << a2[i] << endl;
	}

	return 0;
}



版权声明:本文博主原创文章。博客,未经同意不得转载。