我是否应该为任何与基本类相同的唯一对象创建一个新的子类'对象除默认值外吗?

发布于 2025-02-05 16:21:28 字数 407 浏览 1 评论 0原文

我有一个类:

Class Monster 
{
private:
const int force;
const int prize;
const int damage;
}

在我的代码中,我希望能够轻松地创建一个我称之为龙的唯一怪物对象,该对象具有所有怪物属性的默认值,而这些怪物的属性无法初始化为不同的值(例如:::所有龙的力= 5,奖品= 10,伤害= 10)

我的问题是 - 龙应该是怪物的子类,即使两者之间没有差异,除了默认值和对象的名称?

(实际上我有很多类型,例如龙 - 每个类型都有其自己的默认值)。

看来这将是我需求的一个很好的解决方案,但是我是新手的OOP,并且不确定它是可以接受的,或者如何以不同的方式却优雅地解决它。

I have a class:

Class Monster 
{
private:
const int force;
const int prize;
const int damage;
}

In my code, I want to be able to easily create a unique Monster Object that I call Dragon which has default values for all the Monster's attributes that can't be initialized to different values (for example: all Dragons has force=5, prize=10, damage=10)

My question is- should Dragon be a subclass of Monster even though there is not realy a difference between the two except for the default values and the name of the object?

(In fact I have many types such as Dragon- each has it's own default values).

It seems that this is going to be a fine solution for my needs but I'm new to OOP and not sure it's acceptable or how to solve it differently, yet elegantly.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

被翻牌 2025-02-12 16:21:28

尽管这可能不是最干净的解决方案,但您可以为不同的怪物类型创建enum class,并使用自定义方法调用构造函数。

enum class types {Dragon, Turtle, Squid};

class Monster {
private:
    const int force;
    const int prize;
    const int damage;
public:
    static Monster createMonster(types type) {
        if (type == types::Dragon) {
            return Monster(20, 10, 5);
        }
        else if (type == types::Squid) {
            return Monster(5, 2, 3);
        }
    }
    Monster(int f, int p, int d) : force(f), prize(p), damage(d){};
};


int main(void) {
    Monster dragon1 = Monster::createMonster(types::Dragon);
    Monster squid1 = Monster::createMonster(types::Squid);
    return 0;
}

Although this might not be the cleanest solution, you could create an enum class for your different monster types and use a custom method to call the constructor.

enum class types {Dragon, Turtle, Squid};

class Monster {
private:
    const int force;
    const int prize;
    const int damage;
public:
    static Monster createMonster(types type) {
        if (type == types::Dragon) {
            return Monster(20, 10, 5);
        }
        else if (type == types::Squid) {
            return Monster(5, 2, 3);
        }
    }
    Monster(int f, int p, int d) : force(f), prize(p), damage(d){};
};


int main(void) {
    Monster dragon1 = Monster::createMonster(types::Dragon);
    Monster squid1 = Monster::createMonster(types::Squid);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文