这是代码。
#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 类的构造函数。 我多次检查代码并进行了研究。但我看不出代码有任何错误。 我正在使用带有 GCC 编译器 (MingGW) 的 CodeBlocks IDE。 如果有人可以帮助我,我将不胜感激。 谢谢。
最佳答案
您的 Order 类的构造函数将被调用。
Item items[20]; // <-- here you actually create 20 Items and the constructor for each Item will be called. Then the Order Constructor will get called.
你可以使用 std::list<Item> items;
而不是 Item items[20]
.在这种情况下,您实际上并没有创建项目(因此不会调用它的构造函数),您只是创建了一个容器,您可以在其中存储您的项目。
无论如何,在构造函数中执行您执行的操作是不好的做法。构造函数应该初始化对象并且它应该运行得很快。因此,改为创建一个方法。
关于c++ - 在 C++ 中不调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40653782/