[英]Return types of member functions in C++
非静态成员函数可以与它内部定义的类具有相同的类型吗?
请解释一下,因为我是编程新手
//defining class complex and adding it
class complex
{
private :
int real;
int imaginary;
public:
complex(){}
complex(int x1,int x2);
void display();
complex add(complex n1,complex n2) // can this member function be of complex? type
{
complex temp;
temp.real=n1.real+n2.imaginary;
return temp;
}
}
任何成员函数都可以具有返回类型,即声明它的类类型。 考虑例如operator =
重载。 operator =
是类的非静态成员函数。
complex & operator =( const complex & )
{
// some stuff
return *this;
}
没有这样的限制。 成员函数可以具有普通函数可以接受的任何返回类型。
您的示例将起作用,但是拥有这种add
函数是没有意义的,因为它不会使用调用它的对象的状态。
例如,您将执行以下操作:
complex a,b,c,d;
a = b.add(c,d);
a
将是对c
和d
操作的结果。 不会涉及b
任何内容。
非静态成员函数可以与类名具有相同的类型吗?
* complex add(complex n1,complex n2) // 这个成员函数可以是复杂类型吗
是的,答案很简单
绝对没错。 但是在您拥有函数add()
,它是静态成员函数还是非静态成员函数都没有关系,因为您没有使用调用对象的成员。 您可能会发现编码更具表现力:
complex operator+(complex operand)
{
return complex(real + operand.real, imaginary + operand.imaginary);
}
然后,您将能够以自然且富有表现力的方式使用“+”运算符,例如:
complex a(1,2);
complex b(3,4)
complex c = a + b;
在这种情况下,将为a
调用operator+
方法,并且在运算符的主体内,成员变量real
和imaginary
将隐式成为a
的成员,而b
将由operand
表示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.