无法从类型基类的指针访问派生类方法
我应该指定我对OOP有点新。
我打算做一个类型指针的向量,有一个方法GetName()和访问方法GetSpg()从我的Player类派生Person。我得到一个错误GetSpg()不是Person的成员。我的问题是:有没有办法从向量访问两个函数,如果它指向一个人不显示该方法,但如果这样做?
I should specify that I'm a bit new to OOP. I'm tying to make a vector of type pointer to Person that has a method GetName() and access a method GetSpg() from my Player class that derives Person. I get an error "GetSpg() is not a member of Person". My question would be: is there any way to access both functions from the vector so that if it points to a Person to not show that method but if it is to do so?
这是我的代码:
#ifndef _PERSON_H
#define _PERSON_H
#include <iostream>
#include <algorithm>
typedef std::pair<std::string, std::string> StrPair;
class Person :private StrPair
{
public:
Person(const std::string& fn = "none", const std::string& sn = "none") :StrPair(fn,sn){};
virtual void Update(const std::string& fn, const std::string& sn){ StrPair::first = fn; StrPair::second = sn; };
virtual const StrPair& GetName(){ return (const StrPair&)(*this); };
};
#endif
typedef std::pair<int, int> IntPair;
class Jucator: public Person, private IntPair
{
std::string tip;
int spg;
int average;
public:
Jucator(const std::string& fn = "none", const std::string& sn = "none",
const std::string& t = "", const int& _spg = 0, const int& _avr = 0,
const int& _g = 0, const int& _r = 0) :Person(fn, sn),tip(t),spg(_spg),average(_avr),IntPair(_g,_r){};
virtual void Update(const std::string& fn, const std::string& sn, const std::string& t, const int& _spg, const int& _avr,
const int& _g, const int& _r){
Person::Update(fn, sn); tip = t; spg = _spg; average = _avr; IntPair::first = _g; IntPair::second = _r;
};
virtual const int& GetSpg(){ return spg; };
> Person
类型的指针只能用于访问作为 Person $的一部分的数据/地址c $ c> object。编译器根本无法知道从
Person
中导出的所有类是什么,因此哪些操作是合法的。
You can't.
A pointer of type Person
can only be used to access data/addresses(functions) that are part of the Person
object. The compiler simply has no way of knowing what all classes could be deriving from Person
and hence which operations are legal.
Have a look at Dynamic casting. MSDN Reference | Tutorial
简要说明:
Player* pPlayer = dynamic_cast<Player*>(pPerson);
if (pPlayer) {
//Use the pointer like a player pointer
//Note: You can only call player functions from pPlayer, not pPerson
} else {
//Use the pointer like a person pointer
}
运行时操作。在编译时,编译器会使用 Player
指针访问 Player
代码,它很高兴允许!
Note that this casting is a runtime operation. At compile time, the compiler sees you using the Player
pointer to access Player
code, which it is happy to allow!
免责声明:我发现您的代码很难遵循,因此请考虑这是您在文本中的问题的回答