如何使用抽象类中未包含的方法

How to use method that is not included in abstract class

本文关键字:包含 方法 何使用 抽象类      更新时间:2023-10-16

例如,如果我有一个只有 2 个虚函数的抽象类I_Student:

  • void set() = 0
  • void print() = 0

以及包含其他函数的派生类 Student。

如果我声明的指针类型为 I_Student*,则指向 Student 对象

I_Student* s = new Student();

如何通过指针 s 调用方法而不使它们在 I_Student 中成为纯虚拟?

考虑:

  • Base正在I_Student
  • Derived正在Student

是的,您可以使用类型为 Base*(实际上指向Derived实例(调用Derived类的方法。所以你总是可以投掷另一种方式。

#include <iostream>
class Base
{
public:
    virtual void Foo() = 0;
    virtual void Bar() = 0;
};
class Derived : public Base
{
public:
     void Foo()     { std::cout << "Foo is calledn"; }
     void Bar()     { std::cout << "Bar is calledn"; }
     void FooBar()  { std::cout << "FooBar is calledn"; }
};
int main()
{
    // Example 1 (Assume that basePtr is pointing to a Derived instance)
    {
        Base* basePtr = new Derived;
        static_cast<Derived*>(basePtr)->FooBar();
        delete basePtr;
    }
    // Example 2 (Verify that basePtr is pointing to a Derived instance)
    {
        Base* basePtr = new Derived;
        if (Derived* derived = dynamic_cast<Derived*>(basePtr))
        {
            derived->FooBar();
        }
        delete basePtr;
    }
    return 0;
}

I_Student*访问派生类Student的方法是不可能的,除非先强制转换为Student

Student* s2 = dynamic_cast<Student*>(s);
if (s2 != nullptr)
  ...

您可以通过类调用派生类或学生类的函数I_student只需将函数设置为虚函数即可。一旦一个函数被虚拟化,现在每当它被调用时,它都会根据对象调用它的引用来调用。在这种情况下,指针 's' 的类型是 I_students ,但它具有其父级的引用。这就是调用学生函数的方式。我在这里展示了它

class I_Students
{
public:
    virtual void print()
    {
        cout << "Im I_student"<<endl;
    }
};
class Students :public I_Students
{
public:
    virtual void print()
    {
        cout << "Im student" << endl;
    }
};
int main()
{
    I_Students *s = new Students;
    s->print();
}