我有一个名为Creature
的类,它有三个受保护的变量:string name
、int quantity
和string type
。我有两个派生类Phoenix
和Basilisk
。
我尝试在每个派生类中重新定义一些变量,使其仅成为该派生类的值,但我在尝试重新定义变量的每一行都会出现这些错误。
Error C2059 syntax error: '='
Error C2238 unexpected token(s) preceding ';'
class Creature {
protected:
string name;
int quantity;
string type;
};
class Phoenix : public Creature {
Creature::type = "phoenix";
};
class Basilisk : public Creature {
Creature::type = "basilisk";
Creature::quantity = 1;
};
THis不是有效的c++
class Phoenix : public Creature {
Creature::type = "phoenix";
};
你需要
class Creature {
protected:
string name;
int quantity;
string type;
Creature(string t) :type(t) {}
};
class Phoenix : public Creature {
Phoenix() :Creature("phoenix") {};
};
注意:在类继承结构中存储类型被认为是一种c++代码气味。与其要求类型,不如使用行为。如果它是为了显示的目的,那么规范的做法是有一个类似于"creatureType"的方法,由返回字符串的派生类实现。