尝试在派生类中使用受保护变量时遇到语法错误

发布于 2025-01-21 07:28:17 字数 703 浏览 4 评论 0原文

我有一个名为creature的类,上面有3个受保护变量:字符串名称int dentity字符串类型。我有两个派生的类phoenixbasilisk

我尝试重新定义每个派生类中的某些变量,以使其仅成为该派生类的值,但是我会发现每行的这些错误,我尝试重新定义一个变量。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

东京女 2025-01-28 07:28:17

这不是有效的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") {};
    
};

注意:在类Heirarchy中存储类型被认为是C ++代码气味。使用行为比要求一种类型更好。如果是出于显示目的,则可以这样做的规范事物,以使用一种称为“ createuretype”的方法,就像返回字符串的派生类实现的那样。

THis is not valid c++

class Phoenix : public Creature {
    Creature::type = "phoenix";
};

you need

class Creature {
protected:
    string name;
    int quantity;
    string type;
    Creature(string t) :type(t) {}
};
class Phoenix : public Creature {
    Phoenix() :Creature("phoenix") {};
    
};

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文