我可以像使用父级一样使用继承的类指针吗?
Can I use inherited class pointers just as parent's?
我的两个类:父级和子级(目前)是相同的,并且具有相同的构造函数。
class Parent{
protected:
string name;
public:
Parent(string &n, vector <int> &v) {
/* read n and v into vars */
};
class Child : public Parent {
public:
Child(string &n, vector <int> &v) : Parent(n, v) {}
};
vector <int> val;
string nam, numb;
if(val[0] == 0)
Child* ptr = new Child(nam, val);
else
Parent* ptr = new Parent(nam, val);
myMap.insert(Maptype::value_type(numb, ptr) );
将子* ptr 对象作为父* ptr 对象传递是否合法?我听说它们具有相同的指针类型,所以应该没问题。那我为什么会得到警告:未使用的变量"PTR"警告:未使用的变量"PTR"错误:"PTR"未在此范围内声明?我的程序仅适用于父类。我觉得我没有继承父母的权利。
代码创建两个独立的变量,称为ptr
,这两个变量的作用域都非常有限。
请考虑以下事项:
if(val[0] == 0)
Child* ptr = new Child(nam, val);
else
Parent* ptr = new Parent(nam, val);
它相当于:
if(val[0] == 0) {
Child* ptr = new Child(nam, val);
} else {
Parent* ptr = new Parent(nam, val);
}
// neither of the `ptr' variables is in scope here
以下是修复代码的一种方法:
Parent* ptr;
if(val[0] == 0)
ptr = new Child(nam, val);
else
ptr = new Parent(nam, val);
执行此操作后,还需要确保Parent
具有虚拟析构函数。请参阅何时使用虚拟析构函数?
因为您只在 if 语句中声明了 PTR,所以请尝试在 if 语句的正上方声明它,这样它就可以像 AIX 答案一样
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 我可以像使用父级一样使用继承的类指针吗?