gpt4 book ai didi

c++ - 无法从类型基类的指针访问派生类方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:53:35 26 4
gpt4 key购买 nike

我应该说明我对 OOP 有点陌生。 我试图创建一个指向具有方法 GetName() 的 Person 的指针类型的 vector ,并从派生 Person 的 Player 类访问方法 GetSpg()。我收到错误“GetSpg() 不是 Person 的成员”。我的问题是:是否有任何方法可以从 vector 访问这两个函数,以便如果它指向一个 Person 则不显示该方法,但如果它要这样做?

这是我的代码:

#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 对象的数据/地址(函数)。编译器根本无法知道从 Person 派生的所有类可能是 以及哪些操作是合法的。

看看动态类型转换。 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 代码,它很乐意允许这样做!

免责声明:我发现您的代码难以理解,因此请将此视为对您问题的文本回答

关于c++ - 无法从类型基类的指针访问派生类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23858084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com