我是复制构造函数的新手,当我开始使用向量时似乎无法让它们工作。
// ROBOT CLASS
class Robot {
private:
char *name;
int size;
int cmdCount;
command *cmdList;
char items[8][16];
int resources[3]; // silver, gold, then platinum
public:
Robot( );
Robot(int num_of_cmds, const char *nm);
Robot(const Robot &);
~Robot( );
const char *get_name( );
command get_command(int pos) const;
void set_item(const char item[ ], int pos);
const char *get_item(int pos);
};
// ROBOT CONSTRUCTOR default
Robot::Robot( ) {
// Load Robot name
cmdCount = 5;
try {
name = new char[11];
}
catch(std::bad_alloc) {
cout << "Error allocating " << 11+1 << " bytes of memory\n";
name = NULL;
}
if (name) {
strcpy (name, "univac.dat");
}
// Allocate memory for command array
vector <command> cmdList[5];
};
// ROBOT COPY CONSTRUCTOR
Robot::Robot(const Robot &from) {
cmdCount = from.cmdCount;
// Load Robot name
try {
name = new char[11];
}
catch(std::bad_alloc) {
cout << "Error allocating " << 11+1 << " bytes of memory\n";
name = NULL;
}
if (name) {
strcpy (name, from.name);
}
// Allocate memory for command array
vector <command> cmdList[5];
for (int i=0; i < cmdCount;i++) {
cmdList[i] = from.cmdList[i];
}
for (int i=0; i < 8; i++) {
strcpy(items[i], from.items[i]);
}
for (int i=0; i < 3; i++) {
resources[i] = from.resources[i];
}
}
我在编译时得到的错误是:
robot.cpp:在复制构造函数'Robot::Robot(const Robot&)'中:robot.cpp:117:错误:'cmdList[i] = (((command )from->Robot:中的'operator='不匹配: :cmdList) + ((unsigned int)(((unsigned int)i) * 172u)))' /usr/include/c++/4.4/bits/vector.tcc:156:注意:候选人是:std::vector< _Tp, _Alloc>& std::vector<_Tp, _Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp = command, _Alloc = std::allocator]
我将如何在复制构造函数中复制向量数组?