考虑下课
class test
{
public:
test(int x){ cout<< "test \n"; }
};
Run Code Online (Sandbox Code Playgroud)
现在我想创建50个类测试对象的数组.我不能改变班级考试.
可以在堆或堆栈上创建对象.
在这种情况下,在堆栈上创建obj是不可能的,因为我们在类中没有默认构造函数
test objs(1)[50]; /// Error...
Run Code Online (Sandbox Code Playgroud)
现在我们可以考虑在这样的堆上创建objs ..
test ** objs = NULL;
objs = (test **) malloc( 50 * sizeof (test *));
for (int i =0; i<50 ; ++ i)
{
objs[i] = new test(1);
}
Run Code Online (Sandbox Code Playgroud)
我不想使用malloc.还有其他方法吗?
如果你们想到更多的解决方案,请发布它们......
您无法创建对象数组,如Foo foo [N],没有默认构造函数.这是语言规范的一部分.
要么:
test * objs [50];
for() objs[i] = new test(1).
Run Code Online (Sandbox Code Playgroud)
你不需要malloc().你可以声明一个指针数组.
c++decl> explain int * objs [50]
declare objs as array 50 of pointer to int
Run Code Online (Sandbox Code Playgroud)
但是你可能应该附加某种自动RAII类型的破坏.
OR子类测试公开:
class TempTest : public test
{
public:
TempTest() : test(1) {}
TempTest(int x) : test(x) {}
TempTest(const test & theTest ) : test(theTest) {}
TempTest(const TempTest & theTest ) : test(theTest) {}
test & operator=( const test & theTest ) { return test::operator=(theTest); }
test & operator=( const TempTest & theTest ) { return test::operator=(theTest); }
virtual ~TempTest() {}
};
Run Code Online (Sandbox Code Playgroud)
然后:
TempTest array[50];
Run Code Online (Sandbox Code Playgroud)
您可以将每个TempTest对象视为测试对象.
注意:operator =()©构造函数不是继承的,因此必要时重新指定.