Dra*_*law 5 c++ constructor function
这是一个程序,我试图multi::multi(int, int)在函数中调用类构造函数void multi::multiply().输出是
三十
三十
而不是预期的
三十
25
为什么?
#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;
}
Run Code Online (Sandbox Code Playgroud)
multi (5, 5);
Run Code Online (Sandbox Code Playgroud)
它创建一个临时对象,并在完整表达式结束时被销毁.它不会进行乘法或打印.
要查看所需的输出,可以reset()向类中添加成员函数:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
顺便说一下,在定义构造函数时更喜欢使用member-initialization-list.