【发布时间】: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++