C++ c++;,在子类中,;如何访问父类';没有对象的方法?
我认为只有静态方法可以做以下事情,但它可以工作。 有人能告诉我它是怎么工作的吗?这件事背后的原则是什么C++ c++;,在子类中,;如何访问父类';没有对象的方法?,c++,inheritance,static,C++,Inheritance,Static,我认为只有静态方法可以做以下事情,但它可以工作。 有人能告诉我它是怎么工作的吗?这件事背后的原则是什么 #include <iostream> using namespace std; class Parent { protected: unsigned char* buf; unsigned int bufLenght; public: void Setup() { buf = nullptr; bufLengh
#include <iostream>
using namespace std;
class Parent {
protected:
unsigned char* buf;
unsigned int bufLenght;
public:
void Setup()
{
buf = nullptr;
bufLenght = 0;
cout << "in Parent class Setup()" << endl;
}
virtual void TearDown()
{
delete[] buf;
}
};
class Child : public Parent{
public:
virtual void Setup()
{
Parent::Setup(); // access Parent method without a parent's object?
cout << "in Child class Setup()" << endl;
}
};
int main(int argc, char const *argv[])
{
Child co;
co.Setup();
return 0;
}
#包括
使用名称空间std;
班级家长{
受保护的:
无符号字符*buf;
无符号整数bufLenght;
公众:
无效设置()
{
buf=零PTR;
bufLenght=0;
cout我似乎无法理解您试图实现的目标。您似乎在试图重写的基类方法中忽略了“virtual”关键字,因此收到了来自编译器的错误
虽然您的问题相当不清楚,但下面是我演示如何在C++中实现多态性的最佳尝试:
class A {
protected:
// You will not be able to access this in the
// other class unless you explicitly declare it as
// a 'friend' class.
int m_ProtectedVariable;
public:
// Let's define a virtual function that we can
// override in another class.
virtual void ClassMethod( ) {
printf( "[A::ClassMethod] Called!\n" );
}
}
class B : public A {
public:
// There is no need for the virtual/override keywords
// if you are overloading the function which is already defined
// in another class as 'virtual'. I prefer to keep them for
// pedantic reasons.
/* virtual */ void ClassMethod( ) /* override */ {
//
printf( "[B::ClassMethod] Called!\n" );
// Since the function is a virtual, we can always
// call the base class function.
A::ClassMethod( /* ... */ );
}
}
希望这对你想要实现的目标有所帮助:-)
编辑:在您的特定场景中,您应该在需要时分配一个缓冲区,然后销毁它-为什么不使用类构造函数/析构函数功能?
让编译器决定何时管理内存(在本例中)会更加直观,因为一旦对象超出范围,它将自动发生。每个子对象
都构建在一个父对象
上。只要有子对象
你也有一个父对象否,则没有“在没有父对象的情况下访问父方法”。这将调用此
对象上的父方法。但是“parent::Setup();"在父类中。只有静态方法可以在没有对象的情况下访问。@SamVarshavchik,谢谢你的回答。我仍然感到困惑。这里的这个对象属于子类,而不是父类。现在我们调用父安装方法。我不是指多态性。我想知道如何在没有父对象的情况下访问父方法。@Peter,是的我知道。你说的可以做到:子类object.xxx(父方法)。但这里没有对象,只有“父::设置()