如何修复错误C2259:无法实例化抽象类

How to fix error C2259: cannot instantiate abstract class

本文关键字:实例化 抽象类 何修复 错误 C2259      更新时间:2023-10-16

我正在与虚拟类进行分配,我需要实现纯虚拟方法,后来将在继承的类中实现。

我以前用纯虚拟方法解决了一个问题,这些方法是完美无缺的,我自己解决了我现在收到的错误(错误c2259:'playlist':无法实例化抽象类( - 通过在继承的类中实现一种方法。

class Record
{
    char* artist;
    char* titlu;
    int durata;
public:
    Record()
    {
        artist = new char[50];
        titlu = new char[50];
        durata = 0;
    }
    void setArtist(char *s)
    {
        strcpy(artist, s);
    }
    char* getArtist()
    {
        return artist;
    }
    void setTitlu(char* s)
    {
        strcpy(titlu, s);
    }
    char* getTitlu()
    {
        return titlu;
    }
    void setDurata(int n)
    {
        int durata = n;
    }
    int getDurata()
    {
        return durata;
    }

};
class Playlist
{
    Record* p; /// "Record" is another class
public:
    Playlist(int n)
    {
        p = new Record[n];
    }
    virtual void sortare(int n) = 0;

};
class PlaylistImplementation :public Playlist
{
public:
    void sortare(int n) 
    {
        if (n == 1)
        {
            cout << "1";
        }
        else if (n == 2)
        {
            cout << "2";
        }
        else
            cout << "3";
    }
};

这是主要((:

int main()
{
    int n;
    cout << "Number of tracks ?";
    cin >> n;
    Playlist x(n);  /// I use VS 2019 and "x" has a red tilde underneath, 
                         ///  also error is at this line.
    cin.ignore();
    cin.get();
    return 0;
}

我希望从类播放列表实例化对象。

您无法直接实例化Playlist,因为它是抽象的,因此在main中,而不是:

Playlist x(n);

您需要

PlaylistImplementation x(n);

您需要PlaylistImplementation中的构造函数,例如:

PlaylistImplementation (int n) : PlayList (n) { }

类播放列表中类型记录的成员'p'被隐式声明为私有。对于访问,您需要添加公共成员功能(例如将数据存储到记录中(。