【问题标题】:How to pass an array to a constructor or a class?如何将数组传递给构造函数或类?
【发布时间】:2013-03-28 16:24:16
【问题描述】:

我是 C++ 新手,请帮助我。非常感谢。

我想将一个(新类型数组)传递给一个类。但我收到消息“抛出 bad_alloc 实例后调用 c++ 终止”这是什么意思?再次感谢!!!!

#include <iostream>

using namespace std;

class test {
  public:
      test (int*, int);
       void check ();
  private :
    int k;
     int *a= new int [k];
//int a;

};


int main()
{
  //int a1=5,n=4;
  int n=4;
  int *a1= new int[n];
   //int a1[4]={1,2,3,4};
  test haha(a1,n);
  haha.check();

    return 0;
}


test::test(int *aa, int kk){
a=aa;
k=kk;
}

void test::check()
{
 for(int i=0; i<k; i++){
    cout<<a<<" ";

 }

}

【问题讨论】:

  • Alot? - 更严重的消息是,这段代码甚至不应该编译……你确定这是你要使用的确切代码吗?
  • 这怎么编译??
  • 您是否考虑过使用std::vector 而不是手动分配的数组?这也将解决您在销毁 test 时的 memleak。我还建议将变量命名为更具表现力。关于您的问题:您尝试创建多大的数组? bad_alloc 通常表示内存不足(除非你设法破坏了堆或其他东西)
  • 你可以参考类似的文章,已经在 Stackoverflow 上:[点击这里][1] [1]:stackoverflow.com/questions/9426932/…
  • @Konrad Tsk 用于链接到图像而不是 the article!

标签: c++


【解决方案1】:
class test {
  public:
      test (int*, int);
       void check ();
  private :
    int k;
     int *a= new int [k]; <--- problem, k is undefined + you don't allocate in class declerations
//int a;

};

你不能在类声明中分配.. 尤其是未定义的成员:)

此外..您已经在 c'tor 中分​​配了指针(不是您给它们任何值...)

【讨论】:

    【解决方案2】:

    这些都是您的代码存在的所有问题,按出现的顺序列出。我还为您提供了一些提示:

    1. 非静态数据成员的类内初始化在 C++11 之前的代码中是不允许的。因此这一行是无效的:

      private:
      // ...
          int *a = new int [k];
      //         ^^^^^^^^^^^^^^
      

      不仅如此,这条线是多余的。您已经有一个带有指针的构造函数,并将该指针分配给a。所以这里不需要在课堂上做作业。

    2. test 的构造函数应该在main 之上定义。另外,提示:您应该使用member initializer-list 初始化您的成员。在您的代码中看起来像这样:

      test::test(int *aa, int kk) : k(kk), a(aa) {}
      //                          ^^^^^^^^^^^^^^
      

      冒号后面是你的成员的初始化,每个成员用冒号分隔。

    3. 下面一行是打印ak次的地址

      cout << a << " ";
      

      你不想这样做。您打印一个十六进制数字,表示您的指针指向的内存地址。要打印指针指向的,您必须取消引用指针:

      cout << *a << " ";
      

      注意:您尚未使用任何值初始化数组,因此将打印的所有内容都是堆栈中的垃圾。要为数组分配一些值,您可以这样做(在声明数组的 main 内)

      int *a1 = new int[n];
      
      a1[0] = 1;
      a1[1] = 2;
      a1[2] = 3;
      a1[3] = 4
      

      或者,您可以使用 for 循环:

      for (int i = 1; i <= 4; ++i)
      {
          a1[i - 1] = i;
      }
      

      或者,如果您使用 C++11 进行编译(您可能不是):

      int *a1 = new int[n] {1, 2, 3, 4};
      

      但最重要的是,当您使用完数组后,不要忘记delete[] 您的数组。您使用new/new[] 创建的任何内容都必须删除:

      delete[] a1;
      

      无论如何,您可以通过使用std::vector(恕我直言更好)来避免内存分配和混乱:

      #include <vector>
      
      std::vector<int> a1 = {1, 2, 3, 4};
      

      std::vector 包含有关其大小的信息,这使得传递数组的长度变得不必要。使用向量将大大简化您的程序。

    这就是你的程序:

    #include <iostream>
    #include <vector>
    
    class test {
      public:
          test(std::vector<int>);
          void check();
    
       private:
          std::vector<int> v;
    };
    
    test::test(std::vector<int> temp) : v(temp) {}
    
    void test::check()
    {
       std::vector<int>::const_iterator it;
    
       for (it = v.begin(); it != v.end(); ++it) {
          std::cout << *it << std::endl;
       }
    }
    
    int main()
    {
      std::vector<int> a1 = {1, 2, 3, 4};
    
      test haha(a1);
      haha.check();
    }
    

    Live Demo

    【讨论】:

      【解决方案3】:
      int k;
       int *a= new int [k];
      

      这就是问题所在。创建类实例时,k 未初始化,您将其用作数组大小。

      【讨论】:

      • 因为我无法将 cmets 发布给其他人。 C++11 确实允许非静态成员初始化。为什么大家都说它不应该编译?
      【解决方案4】:

      在你的课堂上:

       int *a= new int [k];
      

      这将导致错误:因为 k 尚未定义。

      error: `test::k' cannot appear in a constant-expression
      error: `new' cannot appear in a constant-expression
      error: ISO C++ forbids initialization of member `a'
      error: making `a' static
      error: invalid in-class initialization of static data member of non-integral type `int*' In constructor `test::test(int*, int)':
      

      您应该从*a 的声明中删除= new int[k],并在构造函数中初始化*a

      【讨论】:

        【解决方案5】:

        您可能应该使用 std::vector 而不是动态内存分配;特别是考虑到您没有删除内存。

        std::vector 非常易于使用,并且有大量可用的文档。见http://en.cppreference.com/w/cpp/container/vector

        示例

        std::vector<int> qux;
        
        qux.push_back(6);
        
        void foo(std::vector<int>& bah)
        {
        
        }
        

        如果你必须传递一个数组,你至少会想要使用 std::array,参见http://en.cppreference.com/w/cpp/container/array

        错误

        std::bad_alloc 是当你的新操作符失败时抛出的异常

        如果你不想让新的 throw 那个异常,你可以使用 std::nothrow,见http://en.cppreference.com/w/cpp/memory/new/nothrow

        您收到此消息的原因是因为您传递了一个未初始化的变量

        【讨论】:

          猜你喜欢
          • 2012-03-14
          • 1970-01-01
          • 2015-12-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-06
          • 2021-08-27
          • 2017-01-02
          相关资源
          最近更新 更多