微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有抽象函数的 C++ 父类,在子类中使用函数

如何解决带有抽象函数的 C++ 父类,在子类中使用函数

我正在尝试创建一个 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++ 实现吗?

解决方法

是的,你可以这样做。您需要将基类中定义的函数设为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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。