Calling Class Constructor in Member Function

感情迁移 提交于 2019-12-10 14:24:53

问题


Here's a program, where I am trying to call the class constructor multi::multi(int, int), in the function void multi::multiply(). The output is

30

30

instead of expected

30

25

Why?

#include <iostream.h>

class multi{
    private:
        int a;
        int b;
    public:
        multi(int m, int n){
            a = m;
            b = n;
        }

        void multiply(){
            cout << "\n\n" << a*b;
            multi (5, 5);
            cout << "\n" << a*b;
        }
};

main(){
    multi x(5,6);

    x.multiply();
return 0;
}

回答1:


multi (5, 5);

It creates a temporary object, and gets destroyed by the end of the full expression. It doesn't do multiplication or printing.

To see the desired output, you can add a reset() member function to your class:

class multi{
    private:
        int a;
        int b;
    public:

        multi(int m, int n) : a(m), b(n) {}   //rewrote it

        void reset(int m, int n) { a = m; b = n; }  //added by me

        void multiply(){
            cout << "\n\n" << a*b;
            reset(5, 5);  //<-------------- note this
            cout << "\n" << a*b;
        }
};

By the way, prefer using member-initialization-list when defining constructors.




回答2:


When you're calling the constructor multi(5, 5) you're actually creating a temporary object that is immediately destructed.




回答3:


This doesn't work, because multi(5, 5); creates a temporary object of class multi, which is immediately destroyed, because it is not used for anything

Since multiply() is a member function of class multi, it has access to the private members, so it can just set a and b directly. You can get your expected output by rewriting multiply like this:

    void multiply()
    {
        cout << "\n\n" << a*b;
        b = 5;
        cout << "\n" << a*b;
    }



回答4:


You can't call constructors like this. What your code does is create a new temporary instance of multi, which gets discarded immediately.

Once an object is constructed, you can't call its constructor again. Create an assign() function or something similar in your class.




回答5:


You can't call a constructor of an already created object. What you are doing in code is, creating a temporary object. Compiler will report error if you do try to do this->multi(5,5).



来源:https://stackoverflow.com/questions/14402097/calling-class-constructor-in-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!