C++里有抽象类指针吗?
巴扎黑
巴扎黑 2017-04-17 12:07:06
0
4
1155

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

巴扎黑
巴扎黑

reply all(4)
阿神

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

洪涛

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 ~

刘奇

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
黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template