这是代码。构造函数不在C++中调用
#include<iostream>
using namespace std;
class Item{
double itemPrice;
int qty;
public:
Item(){
cout<<"Enter Item Price : "<<endl;
cin>>itemPrice;
cout<<"Enter QTY : " <<endl;
cin>>qty;
}
double getItemTotal(){
return itemPrice*qty;
}
};
class Order{
int index;
int orderId;
double orderValue;
Item items[20];
public:
Order(){
index=0;
cout<<"\nEnter Order ID : ";
cin>>orderId;
}
void viewOrderDetails(){
for(int j=0;j<20;j++){
Item ii=items[j];
orderValue=orderValue+ii.getItemTotal();
}
cout<<"Order ID : "<<orderId<<endl;
cout<<"Order Value : "<<orderValue<<endl;
}
void addToOrder(Item i){
if(index<19){
items[index]=i;
index=index+1;
}else{
cout<<"\nOrder Full";
}
}
};
int main(){
Order odr1;
Item i1;
Item i2;
odr1.addToOrder(i1);
odr1.addToOrder(i2);
odr1.viewOrderDetails();
return 0;
}
我想运行Order类的构造函数。 但它运行Item类的构造函数。 我检查了很多次的代码并做了一项研究。但我在代码中似乎没有任何错误。 我正在使用CodeBlocks IDE和GCC编译器(MingGW)。 我很感激有人能帮助我。 谢谢。
一项研究?你发现了什么?你尝试了什么? –
'Order'包含一个20个'Item'的数组,它在'Order'构造函数的主体运行之前被构造。 –
在构造函数中进行任何用户交互通常不是一个好主意。 – molbdnilo