search

Home  >  Q&A  >  body text

C++里有抽象类指针吗?

请问C++有抽象类指针吗?
请问C++有接口类指针吗?
如果有,那么抽象类的指针能指向非抽象的子类对象吗?

巴扎黑巴扎黑2767 days ago1119

reply all(4)I'll reply

  • 阿神

    阿神2017-04-17 12:09:06

    Are you asking the question compared to Java?
    A class with all pure virtual functions is equivalent to a Java interface. You can understand the pointer of this class as an interface class pointer.
    A class with part of pure virtual functions is equivalent to a Java abstract class. The pointer of this class is You can understand it as an abstract class pointer

    C++ actually doesn’t have the concept of interface. I switched from Java to C++. It sounds like what you asked

    Last question, yes, this kind of pointer is often used to implement polymorphism

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 12:09:06

    Pure virtual classes in C++ can be understood as abstract classes ~ This class cannot be instantiated, but it can point to instances of its subclasses that are not pure virtual classes ~

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 12:09:06

    Abstract classes or interface classes are used for this purpose

    #include <iostream>
    using namespace std;
    
    class Base
    {
    public:
        virtual void foo() = 0;
    };
    
    class Child1: public Base
    {
    public:
        virtual void foo() 
        {
            cout << "Child1 foo" << endl;
        }
    };
    
    class Child2: public Base
    {
    public:
        virtual void foo()
        {
            cout << "Child2 foo" << endl;
        }
    };
    
    int main()
    {
        Base *p1 = new Child1();
        p1->foo();
        Base *p2 = new Child2();
        p2->foo();
        return 0;
    }
    

    Output

    Child1 foo
    Child2 foo
    

    reply
    0
  • 黄舟

    黄舟2017-04-17 12:09:06

    It’s a pure virtual function. You can check some blogs on Baidu

    reply
    0
  • Cancelreply