Class C++;具有使用子类中函数的抽象函数的父类

Class C++;具有使用子类中函数的抽象函数的父类,class,c++11,inheritance,Class,C++11,Inheritance,我试图创建一个C++父类,它有两个函数,即代码> f1 < /c>和 f2< /C> >,要在子类中实现。这个父类有一个函数,abstractedFunction,它抽象了f1和f2应该如何一起使用。f1和f2都在子类中实现,如下面的代码所示 #include <iostream> class Parent { public: int f1(); // To be implemented in the derived class void f2(int

我试图创建一个C++父类,它有两个函数,即代码> f1 < /c>和 f2< /C> >,要在子类中实现。这个父类有一个函数,
abstractedFunction
,它抽象了
f1
f2
应该如何一起使用。
f1
f2
都在子类中实现,如下面的代码所示

#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;
}
#包括
班级家长
{
公众:
int f1();//将在派生类中实现
void f2(int i);//在派生类中实现
void abstractedFunction(){//parant类中已抽象
自动r=f1();
f2(r);
}
};
类子:公共父类
{
公众:
int f1(){

std::cout是的,您可以这样做。您需要将基类中定义的函数设置为,然后您可以创建派生类的对象并将其分配给基类指针以进行所需的函数调用


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

#包括
使用名称空间std;
班级家长
{
公众:
虚拟int f1()=0;//要在派生类中实现
虚空f2(int i)=0;//在派生类中实现
void abstractedFunction(){//parant类中已抽象
自动r=f1();
f2(r);
}
};
类子:公共父类
{
公众:
int f1(){
标准::cout