C++虚类之不可实例化

发布时间:2023-12-19 22:56:55

C++中虚类不可以实例化

#include <iostream>
#include <string>
 
using namespace std; 
 
class Pet {
     string name;
public:
     Pet(string p = " ") { name = p; }
     string getName() const { return name; }
     virtual void call() const = 0; //在这里指定虚函数
};
 
class Dog : public Pet{
public:
    Dog(string n) : Pet(n) {}
    void call() const { cout<< "*汪汪叫*" << " "; }
};
 
class Cat : public Pet{
public:
    Cat(string n) : Pet(n) {}
    void call() const { cout << "*喵喵叫*" << " "; }
};
 
void f(Pet *p) {
    p->call();
}
int main() { 
    //Pet pet0("#");    //(1)
    Dog pet1("*");    //(2)
    Cat pet2("$");    //(3)
    f(&pet1);         //(4)
    cout << endl;
    f(&pet2);         //(5)
    return 0;
}

注意!类Pet包含纯虚函数,是一个虚基类,不能直接实例化,因此注释(1)错误;

(2)和(3)中Dog和Cat是派生类,实例化没有问题;

(4)和(5)可以将派生类对象指针转换为指针使用,没问题。

将(1)注释后输出结果:

在这里插入图片描述

文章来源:https://blog.csdn.net/qq_43818724/article/details/135054111
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。