I am new to C++. Could you pls help me get rid of the errors:
error C2259: ‘MinHeap’ : cannot instantiate abstract class
IntelliSense: return type is not identical to nor covariant with return type «const int &» of overridden virtual function function
template <class T> class DataStructure {
public:
virtual ~DataStructure () {}
virtual bool IsEmpty () const = 0;
virtual void Push(const T&) = 0;
virtual const T& Top() const = 0;
virtual void Pop () = 0;
};
class MinHeap : public DataStructure<int>
{
private:
std::vector<int> A;
public:
bool IsEmpty() const
{
..
}
int Top() const
{
..
}
void Push(int item)
{
...
}
void Pop()
{
..
}
};
In silico
50.9k10 gold badges150 silver badges142 bronze badges
asked Sep 20, 2010 at 9:39
softwaremattersoftwarematter
27.8k63 gold badges168 silver badges263 bronze badges
2
The problem is with const T& Top()
vs. int Top()
. The latter is different from the former, and thus not an override. Instead it hides the base class function. You need to return exactly the same as in the base class version: const int& Top() const
.
The same problem exists for Push()
, BTW.
answered Sep 20, 2010 at 9:40
3
try
class MinHeap : public DataStructure<int>
{
private:
std::vector<int> A;
public:
bool IsEmpty() const
{
..
}
const int& Top() const
{
..
}
void Push(const int& item)
{
...
}
void Pop()
{
..
}
};
Note that it is using const int&
instead of int
for Top and Push
answered Sep 20, 2010 at 9:41
Thomas LötzerThomas Lötzer
24.8k16 gold badges68 silver badges55 bronze badges
this is the error message with compiler of visual studio 2010(although it has no problem with compiler of micrsoft visual studio 2003)
error C2259: 'user_param::UserParamB2<std::string>' : cannot instantiate abstract class due to following members:
'bool user_param::UserParamBase::readonly(bool)' : is abstract
c:qcqc_daqsrchfgui3userparambase.h(128) : see declaration of 'user_param::UserParamBase::readonly'
'bool user_param::UserParamBase::readonly(void)' : is abstract
c:qcqc_daqsrchfgui3userparambase.h(127) : see declaration of 'user_param::UserParamBase::readonly'
'SIZE user_param::UserParamBase::winSize(void)' : is abstract
c:qcqc_daqsrchfgui3userparambase.h(129) : see declaration of 'user_param::UserParamBase::winSize'
My source code looks like as follows:
class UserParamBase : public UserParamName
{
public:
virtual bool readonly() =0;
virtual bool readonly(bool bReadonly)=0;
virtual SIZE winSize()=0;
virtual bool get()=0;
virtual void create(CWnd* pParentWnd,const RECT& rect)=0;
virtual void close()=0;
virtual void update()=0;
}
...
template <>
class UserParam< string > : public UserParamB2< string >
{
public:
bool get()
{
AutoCritSec acsWnd(m_csWnd, true);
if(m_wnd.combobox && m_wnd.combobox->GetSafeHwnd()) {
CString text;
m_wnd.combobox->GetWindowText(text);
this->assign((LPCSTR) text);
} else if(m_wnd.wnd && m_wnd.wnd->GetSafeHwnd()) {
char* psz=NULL;
string s;
unsigned uSize = m_wnd.wnd->GetWindowTextLength()+1;
try {
psz=new char[uSize];
m_wnd.wnd->GetWindowText(psz,uSize);
s.assign(psz);
}
catch(...) {
if(psz) delete [] psz;
throw;
}
if(psz) delete [] psz;
s.erase(std::remove(s.begin(),s.end(),'r'),s.end());
this->assign(s);
}
return true;
}
The error message occurs at the this->assign(s);
statement.
asked Dec 20, 2011 at 13:00
user1107855user1107855
2452 gold badges4 silver badges12 bronze badges
2
It’s hard to be specific since you did not post any code, only unformatted compiler output. However, it seems that you created a subclass of a class with abstract methods readonly(bool)
, winSize(void)
and you did not implement these functions in subclass. Therefore, your subclass remained abstract. Implement these methods.
answered Dec 20, 2011 at 13:05
ondriskoondrisko
3202 silver badges11 bronze badges
1
You can’t instantiate an abstract
class, and no one can help you to do that.
You can either:
-
Implement the
class
, but it will no longer be abstract. -
Derive from the
class
, and have the child implement all abstract methods — it seems that this is what you’re trying to do.
An abstract method will look something like:
virtual void foo() = 0;
In your case, the methods UserParamBase::readonly(void)
and UserParamBase::winSize(void)
are abstract in the base class.
You must override them in UserParamB2
and provide an implementation.
answered Dec 20, 2011 at 13:06
Luchian GrigoreLuchian Grigore
252k64 gold badges457 silver badges621 bronze badges
6
description | title | ms.date | f1_keywords | helpviewer_keywords | ms.assetid |
---|---|---|---|---|---|
Learn more about: Compiler Error C2259 |
Compiler Error C2259 |
07/08/2021 |
C2259 |
C2259 |
e458236f-bdea-4786-9aa6-a98d8bffa5f4 |
Compiler Error C2259
‘class‘ : cannot instantiate abstract class
Code declares an instance of an abstract class or structure.
You can’t instantiate a class or structure with one or more pure virtual functions. To instantiate objects of a derived class, the derived class must override each pure virtual function.
For more information, see Implicitly abstract classes.
The following sample generates C2259:
// C2259.cpp // compile with: /c class V { public: void virtual func() = 0; }; class A : public V {}; class B : public V { public: void func(); }; V v; // C2259, V is an abstract class A a; // C2259, A inherits func() as pure virtual B b; // OK, B defines func()
Whenever you derive from an interface and implement the interface methods in the derived class with access permissions other than public
, you may receive C2259. The error occurs because the compiler expects the interface methods implemented in the derived class to have public
access.
To resolve this issue, don’t use more restrictive access permissions for the implementation methods. The compiler doesn’t consider them as implementations for the interface methods defined in the interface. In turn, that makes the derived class an abstract class. Instead, make the access permissions public
for the implemented methods.
C2259 can also occur because of conformance work that was done in Visual Studio 2005, /Zc:wchar_t
is now on by default. In this situation, C2599 can be resolved either by compiling with /Zc:wchar_t-
, to get the behavior from previous versions, or preferably, by updating your types so they’re compatible. For more information, see /Zc:wchar_t
(wchar_t Is Native Type).
The following sample generates C2259:
// C2259b.cpp // compile with: /c #include <windows.h> class MyClass { public: // WCHAR now typedef'ed to wchar_t virtual void func(WCHAR*) = 0; }; class MyClass2 : MyClass { public: void func(unsigned short*); }; MyClass2 x; // C2259 // OK class MyClass3 { public: virtual void func(WCHAR*) = 0; virtual void func2(wchar_t*) = 0; virtual void func3(unsigned short*) = 0; }; class MyClass4 : MyClass3 { public: void func(WCHAR*) {} void func2(wchar_t*) {} void func3(unsigned short*) {} }; MyClass4 y;
The following sample generates C2259:
// C2259c.cpp // compile with: /clr interface class MyInterface { void MyMethod(); }; ref class MyDerivedClass: public MyInterface { private: // Uncomment the following line to resolve. // public: virtual void MyMethod(){} }; int main() { MyDerivedClass^ instance = gcnew MyDerivedClass; // C2259 }
Есть два класса: Effect, FireBall. В main содержится следующий код:
vector<Effect> effects;
...
effects.push_back(FireBall("Огненный шар"))
...
Effect состоит лишь из одного заголовка:
class Effect
{
public:
string name;
virtual void apply(int &value) = 0;
//virtual ~Effect() = 0 {};
};
FireBall.h:
#include "Effect.h"
class FireBall : public Effect
{
public:
int count;
FireBall(string _name);
void apply(int &value);
};
FireBall.cpp:
#include "FireBall.h"
FireBall::FireBall(string _name)
{
count = 10;
name = _name;
}
void FireBall::apply(int &value)
{
value -= 1;
}
На этапе компиляции вылетает ошибка C2259, Effect: невозможно создать экземпляр абстрактного класса
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
// абстрактный класс таблицы произволного вида class abstractTable { protected: char fileName[20];// Имя файла char Name[20];// Фамилия и инициалы char Result[10];// Массив с результатами посещения и сдачи лабораторных работ void HeaderC1() //построение шапки таблицы при помощи Си { printf("n ЪДДДДДДДДДДДДДДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДї"); printf("n і F.I.O. і Lab.# 1 і Lab.# 2 і Lab.# 3 і Lab.# 4 і Lab.# 5 і"); printf("n і ГДДДДВДДДДЕДДДДВДДДДЕДДДДВДДДДЕДДДДВДДДДЕДДДДВДДДДґ"); printf("n і і P. і S. і P. і S. і P. і S. і P. і S. і P. і S. і"); } void HeaderC2() // построение шапкм таблицы при помощи С++ { cout<<endl<<"ЪДДДДДДДДДДДДДДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДВДДДДДДДДДї"; cout<<endl<<"і F.I.O. і Lab.# 1 і Lab.# 2 і Lab.# 3 і Lab.# 4 і Lab.# 5 і"; cout<<endl<<"і і P. і S. і P. і S. і P. і S. і P. і S. і P. і S. і"; } int ProverkaC1(FILE *fp) // проверка файла для Си { if(fp == NULL) { printf(" n Oshibka otkritiya fayla!n Press any key..."); /*_getch(); //функция возвращает код при нажатии любой клавиши*/ return 0; } return 1; } int ProverkaC2i(ifstream &iFile) // проверка чтения файла в С++ { if(!iFile) { cout<<endl<<"Fayl ne nayden!"<<endl<<"Press any key..."; cin.get(); //читает символ перевода строки return 0; } return 1; } int ProverkaC2o(ofstream &oFile) /* проверка записи в С++, вместо этого можно использовать fstream который объединяет первое со вторым*/ { if(!oFile) { cout<<endl<<"Oshibka otkritiya fayla!"<<endl<<"Press any key..."; /* _getch();//Возвращает код символа нажатой клавиши*/ return 0; } return 1; } // Пустые виртуальные функции. virtual void RecordTablC1(char) = 0;// Запись таблицы средствами С virtual void RecordTablC2(char) = 0;// Запись таблицы средствами С++ virtual void ReadPTablC1(char) = 0;// Чтение таблицы средствами С virtual void ReadPTablC2(char) = 0;// Чтение таблицы средствами С++ }; class Tabl: public abstractTable //класс таблицы { public: Tabl(){} //конструктор /*Перегрузки операций помещения в поток и выбор из потока.*/ friend ofstream& operator << (ofstream &outf, Tabl MyTabl) //объявляем дружественную функцию перегружаем операцию << вывода { outf << endl << MyTabl.Name << " " << MyTabl.Result; return outf; } // Для чтения из файла. friend ifstream& operator >> (ifstream &inf, Tabl &MyTabl) { inf >> MyTabl.Name >> MyTabl.Result; return inf; } // Для вывода на экран. friend ostream &operator << (ostream &out, Tabl MyTabl) { cout<<endl<<" ГДДДДДДДДДДДДДДДДДДДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДґ" <<endl<<" і"<<setiosflags(ios::left)<<setw(22)<<MyTabl.Name <<"і "<<setw(2)<<MyTabl.Result[0]<<"і "<<setw(2)<<MyTabl.Result[1] <<"і "<<setw(2)<<MyTabl.Result[2]<<"і "<<setw(2)<<MyTabl.Result[3] <<"і "<<setw(2)<<MyTabl.Result[4]<<"і "<<setw(2)<<MyTabl.Result[5] <<"і "<<setw(2)<<MyTabl.Result[6]<<"і "<<setw(2)<<MyTabl.Result[7] <<"і "<<setw(2)<<MyTabl.Result[8]<<"і "<<setw(2)<<MyTabl.Result[9] <<"і "; return out; } //Для ввода в таблицу. friend istream &operator >> (istream &in, Tabl &MyTabl) { cout<<endl<<" F.I.O. studenta: "; in>>MyTabl.Name; // записывает именна for (int i=0;i<=9;) { cout<<" Posehenie Lab# "<<i/2+1<<"."; in>>MyTabl.Result[i]; while (MyTabl.Result[i]!='-'&& MyTabl.Result[i]!='+') in>>MyTabl.Result[i]; i++; cout<<" Vipolnenie Lab# "<<i/2+1<<"."; in>>MyTabl.Result[i]; while(MyTabl.Result[i]!='-'&&MyTabl.Result[i]!='+') in>>MyTabl.Result[i]; i++; } return in; } /*Запись таблицы средствами Си*/ void RecordTablC1(char Choice) { FILE *fp;// Указатель на поток. system("cls"); // очистка экрана /*printf("n***********************************");*/ printf("n Zapis' tablici sredstvami yazika C.n"); // вывод на экран /*printf("n***********************************");*/ printf("n Vvedite imya fayla!n "); // вывод на экран scanf("%s", fileName); fp=fopen(fileName, "a"); // Создание или открытие существующего файла if(ProverkaC1(fp)==0) return; // Проверка открытия файла // Ввод данных. while(1) // цикл будет повторятся пока истино { system("cls"); // очистка экрана /*printf("n***********************************");*/ printf("n Zapis' tablici sredstvami yazika C.n"); /*printf("n***********************************");*/ printf("n Vvod dannikh.n"); // вывод на экран ввод данных printf(" n F.I.O. studenta: ");// Ввод Ф.И.О. студента scanf("%s", Name); // сохранание введенных данных в массив имени for(int i=0; i<=9; i++)// Ввод данных по посещению и сдаче лабораторных работ { printf("n Posehenie Lab# %d. ",i/2+1); Result[i] = _getch(); // результат равен символу введенной с клавиатуры while(Result[i]!='-' && Result[i]!='+') Result[i]=_getch(); // пока символ не равен + или - то рузельтат будет равен символу введенного с клавиатуры printf(" %c ", Result[i]); // вывод результата посещения л.р. i++; printf("n Vipolnenie Lab# %d. ",i/2+1); Result[i] = _getch(); // результат равен символу введенной с клавиатуры while(Result[i] !='-'&& Result[i] !='+') Result[i]=_getch();// пока символ не равен + или - то рузельтат будет равен символу введенного с клавиатуры printf(" %c ", Result[i]); // вывод результата выполнения л.р. } fprintf(fp, "n%s %s", Name, Result);// Печать введѐнных данных в файл printf( " nn Prodolzhit' vvod?(Y/N)n" );// Запрос на продолжение ввода.; Choice = _getch(); while(Choice !='y' && Choice !='Y' && Choice !='n' && Choice !='N') Choice=_getch(); // пока Choice не равен всем перечисленным буквам он будет равен введенному символу if(Choice == 'n'||Choice == 'N') break; // если Choice равен n или N то выход из цикла } fclose(fp);// Закрытие файла return; } //Запись таблицы средствами С++ void RecordTablC2(char Choice) //функция записи таблицы С++ { system("cls"); // очистка экрана /*cout<<endl<<"*************************************"<<endl;*/ cout<<" Zapis' tablici sredstvami yazika C++."<<endl; // вывод на экран /*cout<<endl<<"*************************************"<<endl;*/ cout<<endl<<" Vvedite imya fayla!"<<endl<<" ";// Ввод названия файла cin>>fileName; ofstream oFile(fileName, ios::app);// Создание потока if(ProverkaC2o(oFile) == 0) return;// Проверка while(1) // бесконечный цикл пока не истино { system( "cls" ); //очистка /*cout<<endl<<"*************************************"<<endl;*/ cout << endl << " Zapis' tablici sredstvami yazika C++" << endl; /*cout<<endl<<"*************************************"<<endl;*/ // Ввод данных cin>>*this; // Запись в таблицу oFile<<*this; cout<<endl<<endl<<" Prodolzhit' vvod?(Y/N)"<<endl; //завершение программы Choice =_getch(); while(Choice !='y'&& Choice!='Y'&& Choice!='n'&& Choice!='N') Choice=_getch();// пока Choice не равен всем перечисленным буквам он будет равен введенному символу if(Choice == 'n'||Choice == 'N') break;// если Choice равен n или N то выход из цикла } oFile.close(); return; //Закрытие файла. } //Чтение таблицы средствами Си void ReadTablC1(char Choice) { FILE *fp;// Указатель на поток. system("cls"); // очистка /*printf("n***********************************");*/ printf( "n Chteniye tablici sredstvami yazika C.nt" ); /*printf("n***********************************");*/ printf( "n Vvedite imya fayla.n " );// Ввод имени файла scanf("%s", fileName); if((fp=fopen(fileName, "r"))==NULL) if(ProverkaC1(fp)==0) return; // Проверка открытия файла fp=fopen(fileName,"r"); // Открытие файла в случае существования HeaderC1(); // Вывод заголовка таблицы // Вывод строк до конца файла while(!feof(fp)) //Возвращает значение true (истина), если достигнут конец файла { fscanf(fp,"n %s %s", Name, Result); //чтение printf("n ГДДДДДДДДДДДДДДДДДДДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДЕДДДДґ"); //вывод Ф.И.О. и результаты по очереди printf("n і %-20.20s і %2c і %2c і %2c і %2c і %2c і %2c і %2c і %2c і %2c і %2c і", Name, Result[ 0 ], Result[ 1 ], Result[ 2 ], Result[ 3 ], Result[ 4 ], Result[ 5 ], Result[ 6 ], Result[ 7 ], Result[ 8 ], Result[ 9 ] ); } printf("n АДДДДДДДДДДДДДДДДДДДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДЩ"); fclose(fp); // Закрытие файла printf("nn Nazmite na lubuyu klavishu..."); Choice=_getch(); return; } //Чтение таблицы средствами С++ void ReadTablC2(char Choice) { system("cls"); // очистка /*cout<<endl<<"*************************************"<<endl;*/; cout<<" Chteniye tablici sredstvami yazika C++n"; /*cout<<endl<<"*************************************"<<endl;*/ cout<<endl<<" Vvedite imya fayla!"<<endl<<" "; // Ввод названия файла cin>>fileName; ifstream iFile(fileName, ios::app); // Создание потока if(ProverkaC2i(iFile) == 0) return; // Проверка HeaderC2(); // печать заголовка таблицы char endF='0'; // создаем переменную типа char и присваиваем ему 0 while(endF!=EOF)//eof определяет достижение конца файла возвращает 1 если текущая позиция конец файла иначе 0 если возвращает -1 значит ошибка { iFile>>*this; cout<<*this; endF=iFile.peek(); //Функция peek() возвращает следующий символ из потока ввода } cout<<endl<<" АДДДДДДДДДДДДДДДДДДДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДБДДДДЩ"<<endl<<endl<<" Press any key..."; Choice = _getch(); iFile.close(); // закрытие файла return; } ~Tabl(){}// деструктор }; int main() { // Вспомогательные переменные: int z = 1; // для выхода из программы; char a, b, c, Choice; // переменные для выбора пунктов. Tabl MyTabl; // создание объекта класса do //условие { system("cls"); // очистка printf("n***********n"); printf("tMain menu.nn 1)Vibor deystviya.nn 2)Exit.nn"); // вывод меню и пунктов printf("n***********n"); a=_getch(); // переменная а равняется значению введенной с клавиатуры if(a=='1'||a=='2') // если а равен 1 или 2 { //Пункт 1. Выбор действия. if(a=='1'){ z=1; system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); do { // Выбор варианта записи. system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); cout << " 1) Zapisat' tablicu.nn 2) Prochtat' tablicu."; b = _getch(); if(b=='1'||b == '2') { if(b=='1') { z = 2; while(z==2) { system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); cout <<"tt1) Zapisat' tablicu.nn"; printf(" 1) Zapisat tablicu sredstvami yazika C;nn 2) Zapisat tablicu sredstvami yazika C++.n"); Choice=_getch(); if(Choice=='1') {MyTabl.RecordTablC1(Choice); z=1;} if(Choice=='2') {MyTabl.RecordTablC2(Choice); z=1;} } } if(b == '2') { // Выбор варианта чтения. z = 2; while(z == 2) { system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); printf("n***********n"); cout << "tt2) Prochtat' tablicu.nn"; printf(" 1) Prochitat' tablicu sredstvami yazika C;nn 2) Prochitat' tablicu sredstvami yazika C++.n"); Choice = _getch(); if(Choice=='1') {MyTabl.ReadTablC1(Choice); z=1;} if(Choice=='2') {MyTabl.ReadTablC2(Choice); z=1;} } } } } while(z!=1); } //Пункт 2. Выход if(a=='2') { z = 2; while((z!=1)&&(z!=0)) { system("cls"); printf("n***********n"); printf("tMain menu(NE RABOTAET!!!)tttnn 1)Vibor deystviya.nn 2)Exit.nn"); //MyFrameC2; printf("ntExit.n Do you want to quit?(Y\N)n"); c = _getch(); if(c=='y'||c=='Y') z=0; else if(c=='n'||c=='N') z=1; else z=2; } } } } while(z!=0); system("cls");//очистка экрана return 0; } |