在成员函数中调用类构造函数 [英] Calling Class Constructor in Member Function

查看:122
本文介绍了在成员函数中调用类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一个程序,其中我试图调用类构造函数 multi :: multi(int,int) :: multiply()。输出为

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

30

而不是预期


30

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


推荐答案

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.

要查看所需的输出,您可以向您的类添加 reset()成员函数:

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

顺便说一句,最好使用 member-initialization-list

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

这篇关于在成员函数中调用类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆