我可以将引用传递给映射,其中数据是指向派生类的指针吗?
Can I pass a reference to a map where the data is a pointer to a derived class?
我想知道是否有可能将引用传递到映射,其中数据是指向派生类的指针?
#include <map>
class B {
public:
private:
int x_;
};
class D : public B {
public:
private:
int y_;
};
typedef std::map<int, B*> mapB_t;
typedef std::map<int, D*> mapD_t;
void foo(mapB_t& inmap) {
;
}
int main() {
mapB_t mapB;
mapD_t mapD;
mapB[0] = new B;
mapD[0] = new D;
foo(mapB);
foo(mapD);
return 0;
}
我收到这个编译错误:
。在函数'int main()'中:q.cc:34:错误:从"mapD_t"类型表达式初始化"mapB_t&"类型引用无效q.cc:22:错误:传递'void foo(mapB_t&)'的参数1
我认为解释应该是,尽管多态性允许将D
类型对象传递给B&
类型引用,但mapB_t
和mapD_t
没有继承关系。因此mapB_t&
不接受mapD_t
。在您的情况下,使用多态性的正确方法可能是创建许多B
和D
类型的对象,但始终将映射定义为mapB_t
类型。B*
类型指针既可以指向B
,也可以指向D
。您需要在B
类中定义至少一个virtual
函数,以允许函数foo
判断由B*
指针指向的对象是B
还是D
。下面是代码:
class B{
private:
int x_;
public:
virtual ~B(){} // Only for telling the identity of an object
};
class D: public B{
private:
int y_; // Virtual destructor gets automatically inherited
};
则函数foo
可以使用dynamic_cast
判断映射找到的对象类型是B
还是D
。下面是代码:
void foo(std::map<int,B*> inmap){
std::map<int,B*>::iterator it=inmap.find([Something]);
D *pd=dynamic_cast<D*>(it->second);
if(pd!=nullptr){
// You know it->second is pointing to an object of type D
}
else{
// Just an ordinary type B
}
}
如果您能做这个问题,您将对多态性有更好的理解:https://www.hackerrank.com/challenges/magic-spells
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 如何使用基类指针引用派生类成员
- 将派生指针分配给C 中的其他派生类型
- 如何通过派生指针调用基类中的模板成员函数
- 如何将带有恒定指针作为参数的模板的派生指针使用
- 无法返回包含派生指针的向量
- 如何创建派生指针类变量
- C++强制转换为派生指针或设计错误
- 无法从派生指针访问公共基成员
- C++发送派生指针作为参数
- 将专用基指针强制转换为专用于其他模板参数的派生指针("adding on"专用化)
- 在派生指针上显式调用基类析构函数时编译错误
- 安全派生指针值的示例
- 安全派生指针的整数表示形式
- c++多态克隆:如何从基指针获得派生指针
- 如果我将派生指针转换为基指针,这两个指针是否保证具有相同的值?
- 以任何方式将基指针强制转换为派生指针是否危险
- 将派生指针隐式强制转换为其相应基类的引用
- 当派生指针仅添加方法时,将基指针强制转换为派生指针的有效性
- c++转换指针到派生指针到基指针的例子