尝试在派生类中使用受保护变量时遇到语法错误
我有一个名为creature
的类,上面有3个受保护变量:字符串名称
,int dentity
和字符串类型
。我有两个派生的类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;
};
I have a class named Creature
with 3 protected variables: string name
, int quantity
and string type
. I have two derived classes Phoenix
and Basilisk
.
I tried redefining some of the variables inside each derived class, so that it becomes that value for that derived class only, but I get these errors for each line I try redefine a variable.
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;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是有效的C ++,
您需要
注意:在类Heirarchy中存储类型被认为是C ++代码气味。使用行为比要求一种类型更好。如果是出于显示目的,则可以这样做的规范事物,以使用一种称为“ createuretype”的方法,就像返回字符串的派生类实现的那样。
THis is not valid c++
you need
NOTE: storing a type in a class heirarchy is considered a c++ code smell. Better to use behavior than to ask for a type. If its for display purposes then the canonical thing to do it to have a method called something like 'creatureType' thats implemented by the derived classes that returns a string.