我有一個問題是可以使用 children 變數來顯示一些東西。
例如:
// Entity.hpp
class Entity {
public:
Entity();
~Entity();
// For this function
virtual void attack();
virtual int getNbAttack();
protected:
private:
int _nbAttack = 0;
int _nbAttackCost = 0;
std::string _msgAttack = "message class Entity";
};
// Player.hpp
class Player : public {
public:
Entity();
~Entity();
protected:
private:
int _nbAttack = 5;
int _nbAttackCost = 5;
std::string _msgAttack = "message class Player";
};
// Entity.cpp
int Entity::attack() {
this->_power -= 10;
std::cout << _msgAttack << std::endl;
return this->_nbAttack;
}
是否可以這樣做:
// Main.cpp
Entity entity;
entity.attack();
std::cout << entity.getNbAttack() << std::endl;
Player player;
player.attack();
std::cout << player.getNbAttack() << std::endl;
結果:
message class Entity
0
message class Player
5
這是可能的還是我必須重寫我的函式?
在此先感謝您的幫助!
uj5u.com熱心網友回復:
你絕對可以做到這一點。但是您需要對發布的代碼進行一些更改:
Entity作為基類添加到的類定義中Player(它在之后丟失public)- 使資料成員
Entity受保護或為它們添加受保護的設定器 - 如果要在派生類中使用基類的建構式,請使用
using Entity::Entity;,但分別Player用Player();和宣告建構式/解構式~Player();。 - 缺少成員變數宣告 (
power) - [可選] 你可以擺脫
this->類內部的訪問成員。您可以使用它,但不是絕對必要的
一般來說,我有兩個提示:
第一:試試看。使用編譯器并運行您的程式。您還可以使用https://godbolt.org/ 之類的頁面來運行您的代碼(請注意,對于初學者來說資訊可能太多)。
第二:獲得一本關于編程語言的好書和/或查看https://en.cppreference.com/w/cpp
uj5u.com熱心網友回復:
你可以這樣做,但至少在我看來,這是一個相當糟糕的主意。
如果您想要兩個在其他方面相似但存盤不同固定值的類,我將使用模板:
#include <iostream>
// This is to represent a string literal, since we can't actually
// pass a string literal as a template argument.
template<size_t N>
struct string_literal {
char data[N];
constexpr string_literal(const char (&input)[N]) {
std::copy_n(input, N, data);
}
operator char const *() const { return data; }
};
template <int N, string_literal name>
class basic_entity {
public:
int attack() const {
std::cout << name << " attack ";
return nbAttack;
}
private:
int nbAttack = N;
};
int main() {
using Entity = basic_entity<0, "Entity">;
using Player = basic_entity<5, "PLayer">;
Entity entity;
Player player;
std::cout << entity.attack() << "\n";
std::cout << player.attack() << "\n";
}
這會產生如下結果:
Entity attack 0
PLayer attack 5
我可以看到兩種值得考慮繼承的情況。首先是您使用的是較舊的編譯器(string_literal該類需要 C 20)。第二個是如果您希望能夠創建一個專案容器,其中每個專案可以是一個Entity或一個Player(或更準確地說,是指向其中一個的指標)。但是,這也可以使用 來實作std::variant<Entity, Player>,這可能是首選的替代方案(特別是,每個專案仍將“就地”分配,而不是需要指向單獨分配專案的指標容器)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/420595.html
標籤:
