非静态成员函数是否可以具有与其内部定义的类相同的类型?

Can a non-static member function have the same type as that of class it is defined inside?

本文关键字:定义 内部 类型 是否 函数 静态成员      更新时间:2023-10-16

非静态成员函数可以具有与其内部定义的类相同的类型吗?

请给我解释一下,因为我是编程新手

//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; 
        }
    }

没有这样的限制。成员函数可以有任何普通函数可以接受的返回类型。

你的例子将工作,但它是没有意义的这种add函数为,因为它不会使用被调用对象的状态。

例如:

complex a,b,c,d;
a = b.add(c,d);

a是对cd进行操作的结果。不涉及b

任何成员函数的返回类型都可以是声明它的类类型。以operator =重载为例。operator =是类的非静态成员函数。

complex & operator =( const complex & )
{
   // some stuff
   return *this;
}

当然可以。但是在您的函数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;

在这种情况下,operator+方法将被a调用,并且在操作符体中,成员变量realimaginary将隐式地成为a的成员,b将由operand表示。

非静态成员函数可以与类名具有相同的类型吗?

* complex add(complex n1,complex n2)//该成员函数是否为复型

是最简单的答案