【发布时间】:2020-02-12 14:38:51
【问题描述】:
这个程序将两个整数相加,程序运行良好(练习要求我使用构造函数和过去的整数)。
但是在构造函数上,如果我初始化 num1 = nbre1 而不是 nbre1 = num1,则程序不起作用。
关于订单的任何解释?
#include <iostream>
int main(){
class op{
public :
int nbre1, nbre2;
op(int num1, int num2){
nbre1=num1;
nbre2=num2;
std::cout<<"numbers initialized";
}
int add(){return nbre1+nbre2 ;}
};
int n1;
int n2;
std::cout<<"Enter the first integer >> ";
std::cin>>n1;
std::cout<<"\n";
std::cout<<"Enter the second integer >> ";
std::cin>>n2;
op addition(n1,n2);
std::cout<<"The sum of the two numbers is >> " << addition.add();
return 0;
}
【问题讨论】:
-
你希望
num1 = nbre1做什么? -
@NathanOliver 超过了构造函数中类的初始化整数。
-
换个角度谈谈 Nathan Oliver 的观点,你对
10 + 1 = x;有何期待? -
完全不相关但有用的功能,在学校似乎很少教授:
op(int num1, int num2): nbre1(num1), nbre2(num2){ std::cout<<"numbers initialized"; }。这是使用the Member Initializer List。当类变得更复杂时,它变得非常重要。例如,它回答了以下问题:当另一个类包含op时,如何将参数传递给op构造函数?
标签: c++ function class constructor initialization