c++ - 在 C++ 中不调用构造函数

标签 c++ constructor

这是代码。

#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/

相关文章:

c++ - 如何在字符串 vector 中找到某个值

C++ 模板对空构造函数的需求

java - 从 Java 构造函数获取变量

c# - C#的lock关键字到C++的转换

c++ - 使用返回另一个翻译单元中定义的占位符类型的函数

c++ - 设计一个环绕的菜单? C++/面向对象

c++ - 作为类成员的结构的 STL 列表

javascript - 为什么 Object.create 比构造函数慢那么多?

c++ - 为什么此 C++ 代码会导致运行时错误?

java - 从构造函数调用可覆盖方法的问题