c++运算符重载 this 指针用法 const用法 超全!

二、成员函数重载

成员函数原型的格式:

函数类型 operator 运算符(参数表);

成员函数定义的格式:

函数类型 类名::operator 运算符(参数表)

{

	函数体;

}

关于this指针:

this是一个隐含的内嵌指针,它指向调用成员函数的当前对象。

this指针是以隐含参数的形式传递给非静态的函数成员的。

this指针除了用于返回当前对象外,还经常出现在非静态的函数成员中。

三、非成员函数重载

友元函数原型的格式:

friend 函数类型 operator 运算符(参数表);

友元函数定义的格式:

函数类型 类名::operator 运算符(参数表)

{

函数体;

}

非静态成员函数后面加const

(加到非成员函数或静态成员后面会产生编译错误),

表示成员函数隐含传入的this指针为const指针,

决定了在该成员函数中,任意修改它所在的类的成员的操作都是不允许的(因为隐含了对this指针的const引用);

唯一的例外是对于mutable修饰的成员。

加了const的成员函数可以被非const对象和const对象调用,但不加const的成员函数只能被非const对象调用。

int f() const
{
	return a;//同return this->a;
}

  #include <iostream>
using namespace std;
class Complex
{
	public:
		Complex(double r=0, double i=0):real(r), imag(i){	}
		Complex operator+( Complex& c )const;//重载双目运算符'+'
		Complex operator-=( Complex& c ); //重载双目运算符'-='
		friend Complex operator-(const Complex& c1,const Complex& c2 );//重载双目运算符'-'
		void Display() const;
	private:
		double real;
		double imag;
};

void Complex::Display() const
{
	cout << "(" << real << ", " << imag << ")" << endl;
}
Complex Complex::operator+( Complex &c) const
{
    Complex tmp;
    tmp.real=this->real+c.real;
    tmp.imag=this->imag+c.imag;
    return tmp;
}
Complex Complex::operator-=(Complex &c)
{
	
    this->real-=c.real;
    this->imag-=c.imag;
    return *this;

}

Complex operator-(const Complex &c1, const Complex &c2)
{
	Complex tmp;
	tmp.real=c1.real-c2.real;
	tmp.imag=c1.imag-c2.imag;
	return tmp;
}

int main()
{
	double r, m;
	cin >> r >> m;
	Complex c1(r, m);
	cin >> r >> m;
	Complex c2(r, m);
	Complex c3 = c1+c2;
	c3.Display();
	c3 = c1-c2;
	c3.Display();
	c3 -= c1;
	c3.Display();
	 return 0;
}

const用法总结

  1. const的作用是使对象不被改写

    -=这个符号会把c3改写所以不加const

  2. const 可以放在函数括号外也可以放在函数括号内
    但是 类内类外必须一致

作为成员函数时

/const/ Time operator+(const Time &t ) const;
第一个const是修饰返回值的,但这样做意义不大,一般不写
第二个const是修饰参数(加法的右操作数)的,表示该函数(加法操作)不会修改参数的内容。如果不加const,则传入const的操作数时就会报错,所以一般要写上
第三个const表示这个函数本身不会修改自身对象(即*this,也是加法的做左操作数)的内容。如果不加cons,则对const的对象调用加法时就会报错,所以一般要写上

作为友元函数时

friend /const/ Time operator+(const Time &t1 ,const Time &t2) ;
第一个const与成员函数的第一个const同理
参数t1相当于成员函数时的*this(加法左操作数),因此其const与成员函数的末尾const同理
参数t2相当于成员函数时的参数t(加法右操作数),因此其const与成员函数的第二个const同理

友元函数末尾不能写const(一定记住!!我刚写的时候一直报错!!!)

猜你喜欢

转载自blog.csdn.net/weixin_44769592/article/details/92377930
今日推荐