[英]How to pass “&player” object into another inherited class constructor (“score”)?
我是C ++的新手,我正在創建一個小程序,以了解有關編程語言繼承的更多信息。
據我所知,繼承是指您有權獲得父級/基類的所有成員函數和值。 現實生活中的類比是繼承了父親父親的一些物理特性,例如眼睛的顏色等(盡管我希望我可以繼承他的商業頭腦……)
無論如何,我想做的一件事就是嘗試將已經初始化的對象傳遞給繼承的類構造函數。
到目前為止,這是我的代碼:
#include <string>
#include <iostream>
using namespace std;
class player{
private:
string name;
int level;
public:
player(const string &n, const int &l) : name(n), level(l){};
string getName() const {return name;}
int getLevel() const {return level;}
};
class score: public player{
private:
int scores;
public:
score(const int &s, const string &n, const int &l) : player(n, l), scores(s){};
void setScore(int newScores){scores = newScores;}
int getScore() const {return scores;}
};
int main(){
player steve("steve", 69);
cout << steve.getName() << endl;
cout << steve.getLevel() << endl;
}
基本上,我想通過我在我已經intialised對象main()
程序函數steve
引用到在構造函數score
類。 但是,我不知道該怎么做? 會像score(const player &p, const int &s) : player(&p), scores(s)
嗎? 我知道如何像成員值一樣傳遞,但是我對傳遞對象本身感興趣?
如果有人可以在這里為我提供幫助,那將意味着很多,因為我真的很喜歡編程,特別是C ++
您不能將基類( player
)的對象擴展到子類( score
)的對象,因為這將需要在原始對象之后直接分配更多的存儲空間來存儲子類的其他元素。
在您的示例中,您可以定義此構造函數,以從player
對象中復制值以創建新的score
對象:
score(const player &p, const int &s) : player(p.n, p.l), scores(s){};
如果只想鏈接播放器對象,則score
類必須包含指向該對象的指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.