gpt4 book ai didi

c++ - C++ 对象中的构造函数继承与方法继承

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:34 24 4
gpt4 key购买 nike

在 C++ 下有没有办法让对象方法继承像构造函数继承一样工作?让我们有以下内容:

(myclass.h)

class B{
public:
B();

void doSomething();
};

class A : public B{
public:
A();

void doSomething();
}

(myclass.cpp)

B::B()
{
executeBCode();
}

void B::doSomething()
{
executeBCode();
}

A::A : B()
{
executeACode();
}

void A::doSomething()
{
executeACode();
}

发生的事情是调用 A 构造函数,我执行 executeBCode(),然后执行 executeACode()。通过对 A 对象调用方法 doSomething(),我只执行 executeACode(),因为它已被覆盖。有没有一种方法可以使方法继承的行为类似于构造函数的继承,从而同时执行派生代码和基本代码?我遇到这个问题是因为我需要代码中的基类为其派生类做一些事情,而且派生类应该执行自己的指令:这只是调用派生类上的 doSomething() 函数.这可能是在 A 上调用的 closeAll() 方法的情况,其中基类关闭其自己的基对象并派生其特定内容。

最佳答案

这不可能直接实现,但是您可以使用 Non-virtual interface idiom 实现足够接近的效果。以下方式:

class A {
public:
void someFunction() {
//put the base's code here
someFuncImpl();//Calls the private function here
//or here, as you see fit
}
private:
virtual void someFuncImpl();//potentially pure: = 0;
};

然后在另一个类中:

class B : public A {
private:
virtual void someFuncImpl() {
//Derived's code goes here
}
};

这样,当您在 B 类上调用 someFunction() 时,您将同时拥有派生类的代码每次执行的基类代码。

这不像构造函数那样简单,但我认为这是最接近和最简单的方法。作为奖励,您可以选择在派生代码之前或之后运行基础代码。

关于c++ - C++ 对象中的构造函数继承与方法继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26670591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com