我可以像使用父级一样使用继承的类指针吗?

Can I use inherited class pointers just as parent's?

本文关键字:继承 一样 指针 我可以      更新时间:2023-10-16

我的两个类:父级和子级(目前)是相同的,并且具有相同的构造函数。

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 答案一样