简体   繁体   English

C++中成员函数的返回类型

[英]Return types of member functions in C++

Can a non-static member function can have the same type as that of class it is defined inside?非静态成员函数可以与它内部定义的类具有相同的类型吗?

Please explain me as I am new to programming请解释一下,因为我是编程新手

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

Any member function can have return type that is the class type where it is declared.任何成员函数都可以具有返回类型,即声明它的类类型。 Consider for example operator = overloading.考虑例如operator =重载。 operator = is a non-static member function of the class. operator =是类的非静态成员函数。

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

There is no such restriction.没有这样的限制。 Member function can have any return type that normal function would accept.成员函数可以具有普通函数可以接受的任何返回类型。

Your example will work, but it makes no sense to have this kind of add function as, as it will make no use of the state of an object it is called upon.您的示例将起作用,但是拥有这种add函数是没有意义的,因为它不会使用调用它的对象的状态。

For example, you will do:例如,您将执行以下操作:

complex a,b,c,d;

a = b.add(c,d);

a will be a result of operation on c and d . a将是对cd操作的结果。 Nothing of b will be involved.不会涉及b任何内容。

Can a non static member function can have same type as that of class name?非静态成员函数可以与类名具有相同的类型吗?

* complex add(complex n1,complex n2) // can this member function be of complex type * complex add(complex n1,complex n2) // 这个成员函数可以是复杂类型吗

Yes is the simple answer是的,答案很简单

Absolutely, yes.绝对没错。 But in the way you have your function add() , it does not matter whether it is a static member function or non-static, as you do not make use of the members of the calling object.但是在您拥有函数add() ,它是静态成员函数还是非静态成员函数都没有关系,因为您没有使用调用对象的成员。 You might find it more expressive to code:您可能会发现编码更具表现力:

complex operator+(complex operand)
{
  return complex(real + operand.real, imaginary + operand.imaginary);
}

Then you will be able to use the '+' operator in a natural and expressive way, for example:然后,您将能够以自然且富有表现力的方式使用“+”运算符,例如:

complex a(1,2);
complex b(3,4)
complex c = a + b;

In this case, the operator+ method will be called for a , and within the body of the operator, the member variables real and imaginary will implicitly be a 's members, and b will be represented by operand .在这种情况下,将为a调用operator+方法,并且在运算符的主体内,成员变量realimaginary将隐式成为a的成员,而b将由operand表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM