无法实例化抽象类错误



我的代码有问题。

我有三个类,其中一个是纯抽象类。 我不知道为什么我会收到错误:

"注意"不能实例化 abstact 类。

可能是因为STL的使用,或者我犯了一个错误,我没有看到它。

问题是我尝试过没有 STL 并且它可以工作,我不知道这里有什么问题,因为我认为它是正确的。

#pragma once
class note
{
protected:
int ziua;
int ora;
public:
note();
note(int day,int hour);
virtual void print()=0;
virtual ~note();
};

#include "note.h"
note::note()
{
}
note::note(int day, int hour) :ziua(day), ora(hour)
{
} 
note::~note()
{
}

#pragma once
#include "note.h"
#include <iostream>
class apeluri:public note
{
char *numar_telefon;
public:
apeluri();
apeluri(int day, int h, char*phone);
void print()
{
printf("%d %d %s", ziua, ora, numar_telefon);
}
~apeluri();
};

#pragma once
#include <iostream>
#include "apeluri.h"
#include <vector>
#include "note.h"
using namespace std;
class remainder
{
vector<note> t;
public:
remainder();
void addsedinta(int zi, int ora, int durata, char*subi);
void addapel(int zi, int ora, char*phon)
{
apeluri *f;
f = new apeluri(zi, ora, phon);
t.push_back(*f);
}
void show()
{
}
~remainder();
};

在您的remainder类中,使用vector<note>是非法的。note是抽象的,因此向量无法创建note对象。

即使note不是抽象的,您的代码仍然无法正常工作,因为它会受到对象切片的影响。

要将派生对象存储在基类的容器中,必须改用指针,即vector<note*>

#pragma once
#include <iostream>
#include <vector>
#include "note.h"
#include "apeluri.h"
using namespace std;
class remainder
{
private:
vector<note*> t;
remainder(const remainder &) {}
remainder& operator=(const remainder &) { return *this; }
public:
remainder();
~remainder()
{
for(std::vector<note*>::iterator i = t.begin(); i != t.end(); ++i) {
delete *i;
}
}
void addsedinta(int zi, int ora, int durata, char*subi);
void addapel(int zi, int ora, char*phon)
{
apeluri *f = new apeluri(zi, ora, phon);
t.push_back(f);
}
void show()
{
}
};

如果您使用的是 C++11 或更高版本,最好这样写:

#pragma once
#include <iostream>
#include <vector>
#include <memory>
#include "note.h"
#include "apeluri.h"
using namespace std;
class remainder
{
private:
vector<unique_ptr<note>> t;
public:
remainder();
remainder(const remainder &) = delete;
remainder& operator=(const remainder &) = delete;
void addsedinta(int zi, int ora, int durata, char*subi);
void addapel(int zi, int ora, char*phon)
{
t.push_back(std::unique_ptr<apeluri>(new apeluri(zi, ora, phon)));
// in C++14 and later, use this instead:
// t.push_back(std::make_unique<apeluri>(zi, ora, phon));
}
void show()
{
}
};

相关内容

最新更新