Hi I’m getting the following error and am really unsure why.
class InteSiVis: public ofBaseApp //{
, public ofxMidiListener{
This occurs when I make class inresivis inherit from the ofxMidiListener class and I get the following error in the main source file
int main( ){
ofSetupOpenGL(1920,1080, OF_WINDOW);
ofRunApp( new InteSiVis()); // <-------- The error is here Allocating object of type abstract
}
This is really confusing as I have tried this with another example in the exact way and do not get this error.
class testApp : public ofBaseApp, public ofxMidiListener {
int main(){
ofSetupOpenGL(640, 480, OF_WINDOW);
ofRunApp(new testApp());
}
Could you give me an idea as to why I’m getting this error I’m calling the class in the exact same way. Thanks in advance.
///———————————-Edit
InteSiVis.h
class InteSiVis: public ofBaseApp //{
, public ofxMidiListener{
public:
InteSiVis() ;
void setup();
void update();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
// Make an Array of Particle Systems
vector<FluidBodySim> mArrayFluidBodySim;
FluidBodySim mFluidBodySim ; ///< Simulation of fluid and rigid bodies
int mStatusWindow ; ///< Identifier for status window
unsigned mFrame ; ///< Frame counter
double mTimeNow ; ///< Current virtual time
int mMouseButtons[3] ; ///< Mouse buttons pressed
bool mInitialized ; ///< Whether this application has been initialized
int mScenario ; ///< Which scenario is being simulated now
// Scene stuff
ofEasyCam mEasyCam;
ofLight light;
// Setting Shader stuff
ofShader shader;
ofxPostProcessing post;
// Sound
float * lAudioOut; /* outputs */
float * rAudioOut;
float * lAudioIn; /* inputs */
float * rAudioIn;
int initialBufferSize; /* buffer size */
int sampleRate;
double wave,sample,outputs[2];
maxiSample piano_A1, piano_AS1, piano_B1, piano_C1, piano_CS1, piano_D1, piano_DS1, piano_E1, piano_F1, piano_FS1, piano_G1, piano_GS1;
vector<maxiPitchStretch<grainPlayerWin>*> stretches;
maxiPitchStretch<grainPlayerWin> *ts, *ts2, *ts3, *ts4, *ts5;
int nAverages;
float *ifftOutput;
int ifftSize;
// // Playing the Wav Files
void audioOut(float *output, int bufferSize, int nChannels);
double speed, grainLength, rate;
ofxMaxiFFT fft;
ofxMaxiFFTOctaveAnalyzer oct;
int current;
double pos;
} ;
testApp.h
class testApp : public ofBaseApp, public ofxMidiListener {
public:
void setup();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased();
stringstream text;
vector<ParticleSystem> ps;
//----------------------Sound---------------------------
void newMidiMessage(ofxMidiMessage& eventArgs);
ofxMidiIn midiIn;
ofxMidiOut midiOut;
ofxMidiMessage midiMessage;
void audioOut(float *output, int bufferSize, int nChannnels);
};
//—————-VIRTUAL FUNCTION
vorticitydistribution.h
class IVorticityDistribution
{
public:
virtual Vec3 GetDomainSize( void ) const = 0 ;
virtual void AssignVorticity( Vec3 & vorticity , const Vec3 & position , const Vec3 & vCenter ) const = 0 ;
} ;
class JetRing : public IVorticityDistribution
{
public:
/*! brief Initialize parameters for a vortex ring (using a different formula from the other).
The vorticity profile resulting from this is such that the induced velocity is in [0,1].
param fRadiusSlug - radius of central region where velocity is constant
param fThickness - thickness of vortex ring, i.e. radius of annular core
param vDirection - vector of ring axis, also vector of propagation
param fSpeed - speed of slug
*/
JetRing( const float & fRadiusSlug , const float & fThickness , const Vec3 & vDirection )
: mRadiusSlug( fRadiusSlug )
, mThickness( fThickness )
, mRadiusOuter( mRadiusSlug + mThickness )
, mDirection( vDirection )
{
}
virtual Vec3 GetDomainSize( void ) const
{
const float boxSideLength = 2.f * ( mRadiusOuter ) ; // length of side of virtual cube
return Vec3( 1.0f , 1.0f , 1.0f ) * boxSideLength ;
}
virtual void AssignVorticity( Vec3 & vorticity , const Vec3 & position , const Vec3 & vCenter ) const
{
} ;
I know questions about this error have been asked repeatedly, however none of the previous answers seem to solve my problem.
I have a pure abstract class ITile
:
class ITile {
public:
virtual ~ITile() {}
virtual void display() = 0;
virtual bool isWalkable() = 0;
virtual bool isGoal() = 0;
};
And three subclasses that all implement these functions like so:
Floor.h
#include "ITile.h"
class Floor : public ITile {
public:
Floor();
virtual ~Floor();
virtual void display() override;
virtual bool isWalkable() override;
virtual bool isGoal() override;
};
Floor.cpp
#include "Floor.h"
#include <iostream>
using namespace std;
Floor::Floor() {}
Floor::~Floor() {}
void Floor::display() {
cout << " ";
}
bool Floor::isWalkable() {
return true;
}
bool Floor::isGoal() {
return false;
}
When trying to compile the whole project I get the following output:
g++ -std=c++0x -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/main.d" -MT"src/main.d" -o "src/main.o" "../src/main.cpp"
In file included from ../src/main.cpp:1:
In file included from ../src/board.h:1:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/vector:265:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/__bit_reference:15:
In file included from /Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/algorithm:627:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/memory:1641:31: error: allocating an object of abstract class type 'ITile'
::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
[...]
…followed by a bunch of notes. But the problem is, I guess, the error in the last line above.
So, what exactly are these algorithm
, memory
files and so on? How can I get rid of this error?
I’m using Eclipse Luna with the C/C++ plugin on Mac OS X (Mavericks) with the Developer Command Line Tools. Any more info gladly given upon request.
Thanks in advance!
TreeInterface.h
#ifndef TreeInterface_h
#define TreeInterface_h
#include"PreconditionException.h"#include"NotFoundException.h"//#include"Tree.hpp"template<class ItemType>
class TreeInterface //: public binarySearchTree<ItemType>
{
virtual void clear()=0;
virtual bool isEmpty()const=0;
virtual int getHeight()=0;
virtual ItemType getRootData() const throw(precondViolated)=0;
virtual bool add(const ItemType& item)=0;
virtual void setItem()=0;
virtual int getNumberOfNodes()const=0;
//virtual ItemType getEntry(const ItemType& anEntry) const throw(NotFoundException)=0;
// int getNumberOfNodes()const;
//virtual void setRootData(const ItemType& item)=0;
//virtual void inorder()=0;
};
#endif /* TreeInterface_h */
Я пытаюсь создать двоичное дерево, но у меня проблема с абстрактным классом. Когда я пытаюсь создать новый экземпляр класса binarySearchTree
это дает мне ошибку: Allocating an object of abstract class type "binarySearchTree"
, Я проверил все свои функции. Я не знаю, что делать. Я думал, что проблема заключается в том, чтобы включить различные файлы, такие как Node.cpp, я не уверен в этом. Я был бы признателен за помощь.
tree.h
#ifndef Tree_h
#define Tree_h
#include"TreeInterface.h"#include"Node.h"//#include"tree.cpp" // should be correct
#include <stdio.h>
#include <iostream>
#include<cstdlib>
#include"PreconditionException.h"#include "NotFoundException.h"using namespace std;
template<class ItemType>
class binarySearchTree: public TreeInterface<ItemType>
{
private:
node<ItemType>* rootPtr;
protected:
int getHeightHelp(node<ItemType>* subTreePtr)const;
void destroyTree(node<ItemType>* subTreePtr);
node<ItemType>* balancedAdd(node<ItemType>* subTreePtr,node<ItemType>* newNodePtr);
node<ItemType>* copyTree(const node<ItemType>* treePtr) const;
public:
binarySearchTree();
binarySearchTree(const ItemType& rootItem);
binarySearchTree(const ItemType& rootItem,binarySearchTree<ItemType>* leftPart,binarySearchTree<ItemType>* rightPart);
binarySearchTree(const binarySearchTree<ItemType>& treePtr);
void clear();
bool isEmpty()const;
int getHeight();
bool add(const ItemType& item);
ItemType getRootData() const throw(precondViolated);
int getNumberOfNodes(node<ItemType>* subtree)const;
void setItem(ItemType item);
};
`
node.h
#ifndef Node_h
#define Node_h
#include <stdio.h>
#include<iostream>
using namespace std;
template<class ItemType>
class node
{
private:
ItemType data;
node<ItemType>* left;
node<ItemType>* right;
public:
node();
node(const ItemType &newdata);
node(const ItemType& item,node<ItemType>* leftPtr,node<ItemType>* rightPtr);
ItemType getNodeItem();
ItemType* getLeftPtr();
ItemType* getRightPtr();
void setLeft(node<ItemType>* newleft);
void setRight(node<ItemType>* newright);
void setNodeItem(ItemType& item);
bool isLeaf() const;
};
Ошибка возникает, когда я пытаюсь создать новый экземпляр binarySearchTree.
main.cpp
#include <iostream>
#include<cstdlib>
#include<string>
#include"Tree.h"using namespace std;
int main()
{
int num=11;
binarySearchTree<int>* node=new binarySearchTree<int>(); //the error is here. Allocating an object of abstract class type "binarySearchTree"node->add(9);
node->isEmpty();
}
-1
Решение
Как указывает xaxxon со ссылкой, если у вас есть абстрактный класс (где виртуальная функция = 0), то все функции в базовом классе должны быть переопределены, чтобы создать экземпляр объекта производного класса. Ваша ошибка компилятора говорит вам, что вы не перезаписали все функции.
В вашем случае ваша проблема немного более тонкая. Учтите следующее:
class Abstract
{
public:
virtual bool MyFunction(int x) = 0;
};
class Concrete : public Abstract
{
public:
bool MyFunction() // This does not override Abstract::MyFunction because it is "overloaded", parameters are different
{
return true;
}
};
int main()
{
Concrete concrete;
return 0;
}
Хотя может показаться, что мы переопределяем MyFunction, это не так, потому что параметры разные (у базового класса int x). Так что это не та же самая функция, и Concrete на самом деле все еще абстрактный класс.
Сравните ваши функции: void setItem(ItemType item);
не собирается переезжать virtual void setItem()=0;
в базовом классе
0
Другие решения
Других решений пока нет …
20 / 20 / 7 Регистрация: 18.02.2015 Сообщений: 304 |
|
1 |
|
23.05.2015, 00:41. Показов 3007. Ответов 3
allocating an object of abstract class type ‘JIntent’
__________________
0 |
939 / 867 / 355 Регистрация: 10.10.2012 Сообщений: 2,706 |
|
23.05.2015, 01:45 |
2 |
как исправить ошибку? Где исправить?
0 |
2758 / 1912 / 569 Регистрация: 05.06.2014 Сообщений: 5,561 |
|
23.05.2015, 05:20 |
3 |
Реализовать pure virtual (=0) методы.
0 |
20 / 20 / 7 Регистрация: 18.02.2015 Сообщений: 304 |
|
23.05.2015, 12:34 [ТС] |
4 |
Intent *JIntent; //Где-то в main.h в функции: //menu.cpp Intent = new JIntent(this); Добавлено через 10 минут
0 |
In file included from /wrkdirs/usr/ports/misc/vxl/work/vxl-2.0.2-682-g9b4d7496d4/core/vil/file_formats/vil_dicom_stream.cxx:5:
/wrkdirs/usr/ports/misc/vxl/work/vxl-2.0.2-682-g9b4d7496d4/core/vil/file_formats/vil_dicom_stream.h:44:16: error: allocating an object of abstract class type 'vil_dicom_stream_factory'
return new vil_dicom_stream_factory(*this);
^
/usr/local/include/dcmtk/dcmdata/dcistrma.h:150:37: note: unimplemented pure virtual method 'ident' in 'vil_dicom_stream_factory'
virtual DcmInputStreamFactoryType ident() const = 0;
^
/wrkdirs/usr/ports/misc/vxl/work/vxl-2.0.2-682-g9b4d7496d4/core/vil/file_formats/vil_dicom_stream.cxx:120:24: error: allocating an object of abstract class type 'vil_dicom_stream_producer'
: DcmInputStream(new vil_dicom_stream_producer(vs))
^
/usr/local/include/dcmtk/dcmdata/dcistrma.h:60:18: note: unimplemented pure virtual method 'eos' in 'vil_dicom_stream_producer'
virtual OFBool eos() = 0;
^
/usr/local/include/dcmtk/dcmdata/dcistrma.h:69:24: note: unimplemented pure virtual method 'avail' in 'vil_dicom_stream_producer'
virtual offile_off_t avail() = 0;
^
- Forum
- General C++ Programming
- abstract class error
abstract class error
The program allows user to choose the implementation( Array-based or LikedList) and then test ADT member functions.
There are 3 files:
-ABCList.hpp
Abstract Data Class declaration with pure virtual functions (no private members)
-ABList.hpp
declaration and definition for Array-based implementation of the list (constructor, obviously few virtual functions)
-LinkedList.hpp
declaration and definition for Poiner-based implementation of the list (constructor, destructor, obviously few virtual functions)
main.cpp {
string input;
ABCList<string> * list;
list = new LinkedList<string>(); //1 error
…
delete list; //2 error
return 0;
}
1 error: «Allocating an object of abstract class type ‘LinkedList».
2 error: «Delete called on ‘ABCList<string>’ that is abstract but has non-virtual destructor».
I have constructor for LinkedList, so the objects can be initialized.
Why does computer think LinkedList is an Abstract Data Type?
What can be the potential problem?
Last edited on
You have a pure virtual member function that’s making your class abstract.
Because you don’t have a virtual destructor, delete list;
will not call `~LinkedList()’ but only `~ABCList()’
Topic archived. No new replies allowed.
Автор | Тема: Сообщение «cannot allocate an object of abstract type» в Qt. Глюк? (Прочитано 8640 раз) |
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||
|
||||||