c++基础--operator+定义在类内仍是在类外

操做符重定义c++

若不用this,操做符应该定义在类外函数

#pragma once
#ifndef _COMPLEX_
#define _COMPLEX_

class complex;
complex&
_doapl(complex* ths, const complex& r);

class complex
{
public:
	complex(double r = 0, double i = 0)
		: re(r), im(i) {};

	double real() const { return re; };
	double img() const { return im; };
	
    //出现问题,vs提示此运算符函数的参数太多
	complex
		operator +(const complex,const complex&);
	//与之相比,+=没有出现问题
	complex&
	operator +=(const complex&);
private:
	double re, im;
};

complex
complex::operator +(const complex&);
#endif

在上述代码中,定义在类内的operator报错this

complex
	operator +(const complex,const complex&);

operator+是一个双目运算符,它的入参应该是两个。定义在类内的时候,每个函数会自动天界一个默认入参this。而很明显 咱们计算复数的时候 y = x + z。这种状况是不须要this的。因此在这种不须要this的状况下,咱们须要将operator+ 定义为全局函数。code

与之相比,+=也为双目运算符,为何它就能定义在类内了呢?blog

由于 y+=z。此时是须要y的值的,也就是说,在真正计算的时候,是须要this的值的,因此应该定义在类内。编译器

编译器会自动检查,若双目运算符定义在类内,则最多只能有一个入参,由于this也算一个。
咱们应该这样定义:编译

#pragma once
#ifndef _COMPLEX_
#define _COMPLEX_

class complex;
complex&
_doapl(complex* ths, const complex& r);

class complex
{
public:
	complex(double r = 0, double i = 0)
		: re(r), im(i) {};

	double real() const { return re; };
	double img() const { return im; };
	
	//与之相比,+=没有出现问题
	complex&
	operator +=(const complex&);

private:
	double re, im;
};

//定义为全局函数
complex
operator +(const complex&){
    
};
#endif
相关文章
相关标签/搜索