[英]Constructor is not called in 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類的構造函數將被調用。
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]
。 在這種情況下,您實際上並沒有創建Item(因此不會調用其構造函數),而只是創建了一個可以存儲項目的容器。
無論如何,在構造函數中執行操作是不好的做法。 構造函數應初始化該對象,並且該對象應運行得很快。 因此,請創建一個方法。
您的訂單類別為:
class Order{
int index;
int orderId;
double orderValue;
Item items[20];
public:
Order(){
// the body of the constructor
您的Order
類包含20個Item
的數組。
在構造函數中的代碼執行之前,必須首先構造所有類成員。
由於您的Order
類包含20個Item
,因此必須首先構造每個Item
,在Order
的構造函數的主體開始執行之前, Item
的默認構造函數將被調用20次。 這就是C ++的工作方式。
這就是為什么您看到Item
的默認構造函數中的代碼明顯在Order
的默認構造函數中的代碼之前執行的原因的解釋。
代替:
Item items[20];
您需要使用向量:
std::vector<Item> items;
並讓addToOrder()
使用push_back()
初始化向量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.