考虑下面的一段代码:
#include <iostream>
using std::cout;
using std::string;
using std::endl;
class SuperPower{
private:
string name;
int category;
public:
string getName(){return name;}
int getCategory(){return category;}
SuperPower(string name, int category){
this->name = name;
this->category = category;
}
};
class Person{
private:
string name, nameRealLife;
SuperPower **powers;
SuperPower *powers2;
int nPowers;
protected:
Person(string name, string nameRealLife){
this->name = name;
this->nameRealLife = nameRealLife;
powers = new SuperPower*[4];
powers2 = new SuperPower[4]("",0);
nPowers = 0;
}
public:
~Person(){
delete []powers;
}
Person(const Person& p){
name = p.name;
nameRealLife = nameRealLife;
powers = new SuperPower*[4];
nPowers = p.nPowers;
for (int i=0;i<nPowers;i++)
powers[i] = p.powers[i];
}
string getName(){
return name;
}
bool addSuperPower(SuperPower &sp){
if (nPowers>=4)
return false;
powers[nPowers++] = &sp;
return true;
}
virtual double getTotalPower(){
double totalPower = 0;
for (int i=0;i<nPowers;i++){
totalPower += powers[i]->getCategory();
}
return totalPower;
}
};
...
我的教授要求解决一个面向对象的问题,我正在努力与编译器完成它,因为这一行:
powers2 = new SuperPower[4]("",0);
尝试编译代码导致错误:数组new中的括号初始值设定项[-fpermissive] powers2 = new SuperPower4;
为什么这是错的?是不是只是定义构造函数的参数?为什么会这样?我该如何解决?
答案 0 :(得分:1)
不要使用原始指针。使用docker pull my/image@sha256:45b23dee08af5e43a7...
。它使生活更轻松。
std::vector
答案 1 :(得分:1)
您可以使用:powers2 = new SuperPower[4]{{"", 0},{"", 0},{"", 0},{"", 0}};
代替powers2 = new SuperPower[4]("",0);
,但不要执行此操作,但我坚持要使用std::vector
这样:
std::vector<Superpower> powers2;
然后在ctor:
powers2(4, Superpower("", 0));