c++, 在子类中,如何在没有对象的情况下访问父类的方法?

c++, In Child class, how can access Parent class's method without a object?

本文关键字:情况下 访问 方法 对象 父类 子类 c++      更新时间:2023-10-16

我认为只有静态方法可以做以下事情,但它可以工作。有人能告诉我它是怎么工作的吗?这背后的原理是什么。

#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;
}

运行此代码,结果是:

在父类Setup((中

在子类Setup((中

我在这里找到答案:如何从派生类函数中调用父类函数?

在用c++思考时,我也发现了同样的描述:但是,当您重新定义函数时,您可能仍然希望调用基类版本。如果在set((内部,您只需调用set((您将得到该函数的本地版本&一个递归函数呼叫若要调用基类版本,必须显式命名使用作用域解析运算符的基类。

每个Child对象都构建在Parent对象之上。每当你有一个Child,你也有一个Parent

我似乎不明白你想要实现什么。您似乎忽略了试图重写的基类方法上的"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( /* ... */ );
}
}

希望你能发现这对你想要实现的目标有帮助:-(

编辑:在您的特定场景中,您应该在需要时分配缓冲区,然后销毁它——为什么不使用类构造函数/析构函数?让编译器决定何时管理内存(在这种情况下(会更直观,因为一旦对象超出范围,就会自动进行管理。