【问题标题】:C++ Parent Class with Abstracted Function that Uses Functions in a Child Class具有抽象函数的 C++ 父类在子类中使用函数
【发布时间】:2021-04-07 13:54:59
【问题描述】:

我正在尝试创建一个 C++ 父类,它有两个函数,f1f2,要在子类中实现。这个父类有一个函数abstractedFunction,它抽象了f1f2 应该如何一起使用。 f1f2 都在子类中实现,如下代码所示。

#include <iostream>

class Parent
{
public:
    int f1();        // To be implemented in the derived class
    void f2(int i);  // To be implemented in the derived class
    void abstractedFunction() { // Abstracted in the parant class 
        auto r = f1();
        f2(r);
    }
};

class Child : public Parent
{
public:
    int f1() {
        std::cout << "f1 is implemented in the child class\n";
        return 1;
    }

    void f2(int i) {
        std::cout << "f2 is implemented in the child class\n";
        std::cout << "Return value for f1 = " << i << "\n";
    }
};

int main() {
    Child ch;
    ch.abstractedFunction();
    return 0;
}

这样的概念可以在 C++ 中实现吗?

【问题讨论】:

    标签: class c++11 inheritance


    【解决方案1】:

    是的,您可以这样做。您需要将基类中定义的函数设为pure virtual : Follow this link to know more about them,然后您可以创建派生类的对象并将其分配给基类指针以进行所需的函数调用

    
    #include <iostream>
    using namespace std;
    
    class Parent
    {
    public:
        virtual int f1()=0;        // To be implemented in the derived class
        virtual void f2(int i)=0;  // To be implemented in the derived class
        void abstractedFunction() { // Abstracted in the parant class 
            auto r = f1();
            f2(r);
        }
    };
    
    class Child : public Parent
    {
    public:
        int f1() {
            std::cout << "f1 is implemented in the child class\n";
            return 1;
        }
    
        void f2(int i) {
            std::cout << "f2 is implemented in the child class\n";
            std::cout << "Return value for f1 = " << i << "\n";
        }
    };
    
    int main() {
        Parent *ptr;
        Child c;
        ptr=&c;
        ptr->abstractedFunction();
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 2019-04-05
      • 1970-01-01
      • 2011-03-21
      • 2014-10-07
      • 2023-03-27
      • 2016-12-12
      • 2010-12-12
      • 1970-01-01
      相关资源
      最近更新 更多