[英]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.