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

时间:2023-05-08
本文介绍了无法从基类类型的指针访问派生类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我应该说明我对 OOP 有点陌生.我要创建一个类型为指向 Person 的向量,该向量具有一个 GetName() 方法,并从派生 Person 的 Player 类访问方法 GetSpg().我收到错误消息GetSpg() 不是 Person 的成员".我的问题是:有没有办法从向量中访问这两个函数,以便在它指向 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 对象的数据/地址(函数).编译器根本无法知道从 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.

看看动态铸造.MSDN 参考 |教程

简而言之:

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!

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

这篇关于无法从基类类型的指针访问派生类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:std::vector 到带有自定义分隔符的字符串 下一篇:C++:围绕某个点旋转向量

相关文章