C++小记(四)

关键词:运算符重载,友元类

友元类

接上一篇结尾,友元类运用较少,但友元函数在运算符重载中扮演重要地位,用全局函数重载运算符都需要声明为友元函数,不然无法访问类中的成员变量

下面举例友元类:

class Complex
{
	friend class A;        //友元类A的声明
private:
	int m_a;
	int m_b;
public:
	Complex();
	Complex(int a, int b);
	bool operator ==(Complex &c);
	bool operator !=(Complex &c);
};

class A
{
private:
	int xxx;
public:
	A(int x)
	{
		xxx = x;
	}
	void print()
	{
		Complex c;
		cout << c.m_a << endl;     //之前声明A为友元类,所以可以访问类Complex中的成员变量
	}
};

各运算符重载

  •   概念所谓重载,就是重新赋予新的含义。函数重载就是对一个已有的函数赋予新的含义,使之实现新功能,因此,一个函数名就可以用来代表不同功能的函数,也就是”一名多用”。
  • 重载的限制:1、不可重载的运算符:  .       ::       .*      ?:       sizeof  
  •                    2、重载运算符函数可以对运算符作出新解释,但原有基本语义不变,不改变运算符的优先级,结合性以及所需要的操作数

下面列出几个常用运算符的重载:

//双目运算符的重载
Complex &operator +(Complex &c1);     //成员函数重载“+”	
friend Complex operator +(Complex &c1, Complex &c2);
// 全局函数重载“+”,所以定义为友元函数才能访问成员函数


bool operator ==(Complex &c);
bool operator !=(Complex &c);
MyString &operator =(const MyString &str);   
MyString &operator +=(const MyString &str);

/****************************************************************/
//单目运算符
Complex operator ++(int);         //成员函数重载后置“++”,后置++不能作为左值,所以不要返回引用Complex &operator ++();               //成员函数重载前置“++”


/****************************************************************/
//其他运算符的重载

friend ostream &operator <<(ostream &out, const MyString &str);   //左移运算符的重载
friend istream &operator >>(istream &in,MyString &str);           //输入不能是const
char &operator [](int index);                                     //[]的重载

其他的类似于   -  ,-- ,(),以此类比。

推荐一个整理较为齐全的博客,仅供参考,如需转载请注明出处:

https://wuyuans.com/2012/09/cpp-operator-overload

重载的注意事项:

  • 运算符运算结果可作为左值的,重载函数需返回引用
  • = [ ]  ( )  ->    只能通过成员函数进行重载
  • C++中用一个占位参数int区分前置++和后置++(--相同)
  • 一般不重载&&,| | ,因为&&和||是C++中非常特殊的操作符,重载的话C++的函数参数都会被求值,无法实现短路规则 
  • 使用成员函数重载时,参数个数减1,因为成员函数默认包含this指针
  •  

猜你喜欢

转载自blog.csdn.net/userkiller/article/details/81233449