【发布时间】:2014-06-22 18:18:53
【问题描述】:
我应该说明我对 OOP 有点陌生。 我正在尝试创建一个指向具有 GetName() 方法的 Person 类型指针的向量,并从派生 Person 的 Player 类访问方法 GetSpg()。我收到错误消息“GetSpg() 不是 Person 的成员”。我的问题是:有没有办法从向量中访问这两个函数,这样如果它指向一个 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; };
【问题讨论】:
-
你永远不能从基类指针访问派生类方法,但是你可以反过来做
-
class Jucator: public Person, private IntPair其中typedef std::pair<int, int> IntPair。继承 STL 比和魔鬼做交易更糟糕。 -
我希望人们不要认为这“太琐碎”。我从经验中知道,很多人,尤其是从 Web 技术转向 C++ 的人,觉得这有点令人困惑。
-
@Sharadh 我不确定用户想要完成什么,他是在搜索矢量
还是他自己的类?为什么多态在这里没有帮助?我很困惑 -
@Marco 我也不确定,从他的代码。然而,从他所说的来看,他需要铸造和使用它。这里的多态性(我的意思是亲自拥有 GetSpg() 的存根实现,它什么都不做)似乎是人为的。我们在派生类之一中使用完全不相关的函数污染了基类。我看不到向量 OP 所指的位置正在使用。如果 OP 可以解释他的用例,也许我们可以做得更好?
标签: c++ oop vector stl dynamic-programming