C++中类内成员函数什么时候用void,什么时候用类名定义
void表示没有返回值,用类名定义的只有返回自身类型的才需要,
比如复数类complex,重载加减乘除运算的时候,返回值都是complex
参考如下:
#include <iostream>
using namespace std;
class complex
{
private:
double real,image;
public:
complex()
{
real = 0;
image = 0;
}
complex(double r,double i)
{
real = r;
image = i;
}
~complex(){}
void print() //这里用的是void,因为没有返回值
{
cout << real << "+"<<image <<"i"<<endl;
}
complex operator +(complex &a) //这里的返回值是complex,因为返回的结果仍然是complex类型
{
complex c;
c.real = this->real + a.real;
c.image = this->image + a.image;
return c;
}
};
int main()
{
complex a(3,4);
complex b(2,1);
complex c = a+b;
return 0;
}
这两不是一个东西啊