我想知道当对象需要将构造函数传递给它时是否可以创建一个对象数组.我想要这样的东西:
MyClass *myVar;
myVar = new MyClass[num]; // I would like to specify the array size after declaration
int i = 0;
for(i = 0;i < num;i++)
myVar[i] = new MyClass(0,0); // I would also like to populate the array with new objects
Run Code Online (Sandbox Code Playgroud)
我知道这有效:
MyClass *myVar;
myVar = new MyClass[num];
Run Code Online (Sandbox Code Playgroud)
但这仅在构造函数没有传递给它时才有效.我正在尝试做什么?如果是这样,我该怎么办?
编辑:我发现如何使用数组.我是这样做的:
MyClass **myVar;
myVar = new MyClass *[num];
for(i = 0;i < num;i++)
myVar[0] = new MyClass(0,0);
Run Code Online (Sandbox Code Playgroud)
我会使用矢量等,但我的老师告诉我们尽可能使用基本数组.上面的解决方案我实际上是从老师写的一些代码中得到的.感谢大家的帮助!
我正在尝试用C++创建一个应用程序.在应用程序中,我有默认构造函数和另一个带有3个参数的构造函数.用户从键盘提供一个整数,它将用于使用非默认构造函数创建对象数组.不幸的是,到目前为止我还没有完成它,因为我遇到了创建对象数组的问题,他们将使用非默认构造函数.有什么建议或帮助吗?
#include<iostream>
#include<cstring>
#include<cstdlib>
#include <sstream>
using namespace std;
class Station{
public:
Station();
Station(int c, char *ad, float a[]);
~Station();
void setAddress(char * addr){
char* a;
a = (char *)(malloc(sizeof(addr+1)));
strcpy(a,addr);
this->address = a;
}
void setCode(int c){
code=c;
}
char getAddress(){
return *address;
}
int getCode(){
return code;
}
float getTotalAmount(){
float totalAmount=0;
for(int i=0;i<4;i++){
totalAmount+=amount[i];
}
return totalAmount;
}
void print(){
cout<<"Code:"<<code<<endl;
cout<<"Address:"<<address<<endl;
cout<<"Total Amount:"<<getTotalAmount()<<endl;
cout<<endl;
}
private:
int code;
char *address;
float amount[4];
};
Station::Station(){
code= 1; …Run Code Online (Sandbox Code Playgroud) c++ ×2