我对 C++ 非常陌生。我有这样的情况:我有一个包含两个虚函数(不是纯函数)的基类。我有一个该类的派生类,我在其中实现了这些虚函数。现在在我的 main() 函数中,我创建了一个指向基类指针对象的指针。现在使用这个对象如何访问派生类对象和函数。
我只想使用指向基类指针对象的指针来访问派生类对象。
基础类:
class another
{
public:
virtual void setName(){};
virtual string getName(){};
};
派生类
class use: public another
{
public:
string str;
void setName()
{
str = "USE CLASS";
}
string getName()
{
return str;
}
};
我的 main() 函数:
int main()
{
another **an;
*an = new use();
an->setName(); //getting error
cout<<an->getName()<<endl; //getting error
return 0;
}
最佳答案
*an = new use();
指针 an
未初始化,无法取消引用。使用双指针(指向指针的指针)在这里没有实际意义。在这种情况下,tit 所做的只是为代码添加另一个级别的引用。取消引用此类指针的表达式导致指向类“另一个”的指针的值存储在...在哪里?您从未创建过该存储,因此此类操作是一个 UB。
代码的合法变体:
int main()
{
another **an = new another*(); // creating storage for pointer
*an = new use();
(*an)->setName();
cout<<(*an)->getName()<<endl;
delete *an; // don't rely on OS to do so.
delete an;
return 0;
}
int main()
{
another **an = new another*(new use()); // doing this in one line
// storage of *an would be value-initialized by value returned
// from 'new use()' instead of default initialization
(*an)->setName();
cout<<(*an)->getName()<<endl;
delete *an; // don't rely on OS to do so.
delete an;
return 0;
}
int main()
{
another *an = new use();
// We don't need another pointer~ use an reference where required?
an->setName();
cout<<an->getName()<<endl;
delete an; // don't rely on OS to do so.
return 0;
}
附言。这个 another
类的声明在技术上是错误的,我可以假设你已经跳过了 getName 的主体。它应该导致有关函数缺少返回值的编译时错误。如果 another
本身是不可用的类,您可以将方法声明为纯方法
class another
{
public:
virtual void setName() = 0;
virtual string getName() = 0;
};
无法创建此类类或派生类的实例,但不重写这些方法,但它提供了您正在研究的“样板”机制。
关于c++ - 在 C++ 中将派生类对象分配和访问到基类 "pointer to pointer"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42992522/