在基类指针向量中,如何访问派生的类成员返回错误
How come accessing derived class member in base class pointer vector returns an error?
问题的简化示例:
#include <string>
#include <deque>
#include <iostream>
class Action{
public:
std::string name;
Action(std::string name){
this->name = name;
}
};
class Ability : public Action{
public:
int bar;
Ability(std::string name) : Action(name){}
};
int main(){
std::deque<Action*> foo;
Ability test("asdf");
test.bar = 122;
foo.push_back(&test);
std::cout << foo.at(0)->bar << std::endl;
return 0;
}
这会产生一个错误,即"动作"没有" bar"成员。
我意识到这与对象切片有关,并且我试图使用指针,这使矢量可以推回"能力"对象,但我无法访问其" bar"成员。
我缺少什么?
首先,我们的赞助商的单词:什么是对象切片?
既然您已经阅读了上述链接,则可以看到由于对象未复制到foo
中,因此没有切片,只复制了对象的指针。Ability
仍然完好无损,无论在内存中坐着 test
中的任何地方。
但是... foo包含Action
的指针,而不是Ability
。Foo
的用户无法知道Foo
的任何给定元素是否是对Action
,Ability
或其他Action
的其他子类的引用,他们绝对不知道。非常有力的东西,能够与您甚至不知道的事物一起工作的能力,但这是有代价的:您必须像知道的东西一样使用它。Foo
的用户只能使用Action
的界面。在此方面有很多方法,例如Dynamic_cast,但是在大多数情况下,最好坚持使用所提供的接口,并允许超载的方法或操作员在场景后面做黑魔法,以对Action
代表的任何方法做正确的事情。如果这意味着您必须
class Action{
public:
std::string name;
Action(std::string name){
this->name = name;
}
virtual int getbar() = 0; // pure virtual method that all subclasses
// of Action must implement
};
class Ability : public Action{
public:
int bar;
Ability(std::string name) : Action(name){}
int getbar()
{
return bar;
}
};
及以后
std::cout << foo.at(0)->getbar() << std::endl;
这样。
相关文章:
- 如何使用单独文件中的派生类访问友元函数对象
- 为什么此派生对象无法访问基类的后递减方法?
- C++:为什么无法在派生类中访问受保护的构造函数?
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 派生的 wxPanel 控件如何访问其中包含 wxDialog 中的数据?
- 从纯虚拟类 (A) 派生的指针无法访问来自纯类 (B) 的重载方法
- C ++基础私有方法在将自身转换为派生类后可以访问吗?
- 按基类对象访问派生类资源时出错
- 使(虚拟)函数在大多数派生类中无法访问中间基类中可访问,定义良好?
- 从模板化父类中的派生内部类访问受保护的成员变量
- 如何从派生类访问基类中的重载运算符?
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- C++11: 如何访问派生类中的基类成员?
- 访问派生类的 QMetaObject
- 使用基类对象访问派生的仅类方法
- 如何在 c++ 中通过基类引用访问派生类的对象?
- 派生类无法访问基类的受保护成员
- 如何在 c++ 中使用多态性访问派生类字段?
- 为了访问方法,从基类动态转换为派生类
- C++继承从基类指针访问派生类中的非虚拟函数