My code is like this:
Basic.h
#define Type double
Model.h
#include "Basic.h"
class Model{
protected:
int _N;
public:
Model(int _N, Type* config){ config=new Type[N]; _N=N}
virtual Type compute();
}
class Model1: public Model{
protected:
int _Nr,_Nc;
public:
Model1(int Nr, int Nc, Type* config):Model(Nr*Nc,config){_Nr=Nr;_Nc=Nc;}
virtual Type compute();
}
class Model2: Public Model{
public:
Model2(int N,Type* config):Model(N,config){/*other unrelated codes*/}
virtual Type compute();
}
Model1.cpp
#include "Model.h"
Type Model1::compute(){
/*definition*/
}
Model2.cpp
#include "Model.h"
Type Model2::compute(){
/*definition*/
}
Method.h
#include "Model.h"
void Method(Model* sys);
Method.cpp
#include "Method.h"
void Method(Model* sys){
Type a=sys->compute();
/*code*/}
Main.cpp
#include "Method.h"
int main(int argc, char** argv){
Model* sys=new Model2();
Method(sys);
/*code*/
}
I can't find any problems but the compiler keeps complaining "error LNK2019: unresolved external symbol void __cdecl Method(class Model *) referenced in function _main".
I am so frustrated because I am a beginner of this and fail to find out the key. I don't know what can cause this: is it anything wrong in my #define? Or it is because different subclass have functions with the same name(seems it should be OK)? Or there is other bugs? I don't even know to add what tags to this question...
Can anyone help me to figure this out? Thanks a lot!
Thanks for suggestions and I have updated the questions to make sure all the constructors are contained.
It seems as if Method.cpp is not part of the project, so it's not compiled and the linker can't find Method.
You should add all CPP files to your project - Main, Method, Model1 and Model2. While you're at it, make sure the H files are all there, as well.
Missing some semicolons in the Model.h I think.
You need to end the class definitions with semicolon.
For example:
class Model{
protected:
int _N;
public:
Model(int _N, Type* config){ config=new Type[N]; _N=N}
virtual Type compute();
};
Not sure if this is the solution to your problem however. But missing semicolons can bring up all sorts of issues.
Related
Aaand im back again with my second question and im kinda not sure about wether i should have posted all the seperate classes cuz it looks somewhat long. And im sure the solution is pretty small.
Anyways, i am at polymorphism tutorial vid that i am following and everything works fine if i follow it and put all classes in "main.cpp". But when i tried to do the same program with seperate classes (seen below) i am getting error "
E:\Codeblocks\Poly\main.cpp|11|error: cannot convert 'Ninja' to 'Enemy*' in initialization|".*
I kinda understand what the error is saying..i think.. but dont know what i did wrong since the same code was working when Enemy and Ninja class wasnt seperate but now as seperate classes its not working. I think i included those classes properly in main.cpp.
main.cpp
#include <iostream>
#include "Enemy.h"
#include "Ninja.h"
#include "Monster.h"
int main()
{
Ninja n;
Monster m;
Enemy *enemy1=&n;
Enemy *enemy2=&m;
enemy1->setAttackPower(20);
enemy2->setAttackPower(50);
n.attack();
m.attack();
return 0;
}
Enemy.h
#ifndef ENEMY_H
#define ENEMY_H
class Enemy
{
public:
Enemy();
void setAttackPower(int a);
protected:
int attackPower;
private:
};
#endif // ENEMY_H
Enemy.cpp
#include "Enemy.h"
Enemy::Enemy()
{
//ctor
}
void Enemy::setAttackPower(int a)
{
attackPower=a;
};
Ninja.h
#ifndef NINJA_H
#define NINJA_H
class Ninja
{
public:
Ninja();
void attack();
protected:
private:
};
#endif // NINJA_H
Ninja.cpp
#include "Ninja.h"
#include <iostream>
Ninja::Ninja()
{
//ctor
}
void Ninja::attack(){
std::cout<<" I am a ninja. Ninja chop! -"<<attackPower<<"\n";}
This is because your Ninja class is not inhereted from Enemy class. You must define Ninja class like this:
#include "Enemy.h"
class Ninja : public Enemy
{
public:
Ninja();
void attack();
protected:
private:
};
EDIT: I added #include directive. Without it compiler won't know, where to find Enemy class declaration.
I have two classes: AbstractClass and SubClass.
This is basically my code (well, just some example code):
abstractclass.h
class AbstractClass
{
public:
AbstractClass();
void doSomething();
protected:
virtual void implementMe() = 0;
int a;
};
abstractclass.cpp
#include "abstractclass.h"
AbstractClass::AbstractClass(){}
void AbstractClass::doSomething()
{
implementMe(); // compiler error: "implementMe() was not declared in this scope"
a = 0; // same compiler error here...
}
subclass.h
#include "abstractclass.h"
class SubClass : public AbstractClass
{
public:
SubClass();
protected:
void implementMe();
};
subclass.cpp
#include "subclass.h"
SubClass::SubClass() {}
void SubClass::implementMe()
{
// do some stuff
}
In the AbstractClass, however, I keep getting a compiler error (for the virtual function as well as for the class variable):
implementMe() was not declared in this scope
The only way I found to get rid of this was to use forward-declaration:
void implementMe();
AbstractClass::doSomething()
{
implementMe();
}
I cannot believe that this is the correct way, though?
Thanks!
EDIT:
Ok, as my conceptual understanding of subclassing in C++ doesn't seem to be totally wrong (see the comments), I'm gonna share some of my original source code. Hopefully this will help to indentify the error.
This is my abstract / base class:
abstractenvironment.h
#ifndef ABSTRACTENVIRONMENT_H
#define ABSTRACTENVIRONMENT_H
#include <QObject>
class AbstractEnvironment : public QObject
{
Q_OBJECT
public:
AbstractEnvironment(QObject *parent = 0);
protected:
virtual void process() = 0;
quint32 counter;
private slots:
void handleTimeout();
};
#endif // ABSTRACTENVIRONMENT_H
abstractenvironment.cpp
#include "abstractenvironment.h"
#include <QTimer>
QTimer *myTimer;
AbstractEnvironment::AbstractEnvironment(QObject *parent) :
QObject(parent)
{
myTimer = new QTimer(this);
connect(myTimer, &QTimer::timeout, this, &AbstractEnvironment::handleTimeout);
myTimer->start(1);
counter = 0;
}
void handleTimeout()
{
process();
counter++;
}
And this is my subclass:
environment.h
#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
#include "abstractenvironment.h"
class Environment : public AbstractEnvironment
{
Q_OBJECT
public:
Environment(Controller *controller, QObject *parent = 0);
protected:
void process();
};
#endif // ENVIRONMENT_H
environment.cpp
#include "environment.h"
Environment::Environment(Controller *controller, QObject *parent) :
AbstractEnvironment(controller, parent) {}
void Environment::process()
{
// do something
}
PS: I've learned from the first part of this question and tried to compile the source code above inside Qt with MinGW. I get exactly two error messages (as expected):
..\untitled\abstractenvironment.cpp: In function 'void handleTimeout()':
..\untitled\abstractenvironment.cpp:17:13: error: 'process' was not declared in this scope
..\untitled\abstractenvironment.cpp:18:5: error: 'counter' was not declared in this scope
In case you want to try it yourself, I've zipped the Qt project and uploaded it to my Dropbox (of course I will remove this file at some point but the code is exactly the same as in the post above --> it's just for the sake of convenience, so you don't have to copy-paste it yourself)
EDIT: You just changed your question. So I can't tell if your original text was your actual source code or not. Good rule of thumb, paste your actual code rather than paraphrase it (then de-identify or reduce it if needed).
ORIGINAL ANSWER:
implementMe(); // compiler error: "implementMe() was not declared in this scope"
That is because doSomething() isn't declared properly in AbstractClass. You "declared" it in the base class with:
doSomething();
The compiler doesn't recognize AbstractClass::doSomething() out of line definition so nothing inside the implementation is resolved to the class scope.
Change that to:
void doSomething();
just like in your derived class.
and
AbstractClass::doSomething()
{
implementMe();
}
to
void AbstractClass::doSomething()
{
implementMe();
}
UPDATE:
void handleTimeout()
{
process();
counter++;
}
is a global function. That isn't the class implementation. It should be:
void AbstractClass::handleTimeout()
{
process();
counter++;
}
In abstractenvironment.cpp you define void handleTimeout(), which is non-member function and does not relate to AbstractEnvironment class. Thus, it doesn't look for AbstractEnvironment::process() and AbstractEnvironment::counter, but for ::process() and ::counter instead (which are not declared, hence the error).
Change it to void AbstractEnvironment::handleTimeout() and it should compile.
I am working on a homework problem where we have to use inheritance. (I'm not very good with inheritance yet). We are to make a parent class "card_games" that has two children classes called "gofish" and "poker". We are given a template that our main has to follow, and the rest of the design is up to us. Here is my header file: (called "classes.h")
#include <vector>
using namespace std;
struct cards{
int rank;
char suit;
};
class players{
public:
int points;
int active;
vector<cards> cardhand;
void printhand(players *gameplayers, int person);
};
class card_games{
protected:
players *gameplayers;
void player_make();
public:
virtual void play();
};
class poker :public card_games{
public:
void play();
};
class gofish :public card_games{
public:
void play();
};
void player0_play(players *gameplayers, cards *cardlist, int people);
void createdeck(cards *cardlist);
void shuffle(cards *cardlist);
void deal(cards *cardlist, int people, players *gameplayers);
int getplayers();
I have determined the error is something to do with my virtual call. The error specifically is:
cardgames_play.obj : error LNK2001: unresolved external symbol "public: virtual void __thiscall card_games::play(void)" (?play#card_games##UAEXXZ)
And I believe this causes my next error of:
card_games.exe : fatal error LNK1120: 1 unresolved externals
Anyway something is wrong with my virtual void function.
Here is my main function:
#include <iostream>
#include "classes.h"
int main(){
card_games *game;
int opt;
game = NULL;
cout << "Poker 1, Go Fish 2" << endl;
cin >> opt;
if (opt == 1)
game = new poker;
else if (opt == 2)
game = new gofish;
game->play();
return 0;
}
We are supposed to roughly use this template. If I understand it correctly, I am creating an instance of Card_game class called game, then assigning game to an instance of either gofish or poker. Then I dereference "game" to the "play();" function. The rest of my code, I have a
void gofish::play(){
blah blah
}
and a
void poker::play(){
blah blah
}
Which have the rest of my code that works.
Any help regarding this error is greatly appreciated. Thanks!
P.S. I am using visual studio 2013 on windows 8.
The method void play(); in card_games does not have a body, and it is not pure virtual. Just do the change:
class card_games{
protected:
players *gameplayers;
void player_make();
public:
virtual void play()=0; //make it pure virtual
};
So I have been having this extremely frustrating problem lately with Visual C++ 2012. Up until a few hours ago, I was writing code just fine and everything was working as intended, until I decided to optimize some things and deleted a few classes. I fixed all of the errors that were popping up because of that, e.g. false includes, etc. Unfortunately, after this the VS compiler went crazy. It started giving me errors such as:
Error 14 error C2653: 'Class' : is not a class or namespace name
or even
Error 5 error C2143: syntax error : missing ';' before '}'
Error 4 error C2059: syntax error : '>'
I've checked multiple times, and everything is in it's right place: all headers included, all symbols placed where they should be.
As far as I understand, the problem is not with my code but with the compiler itself... Visual Studio can be really annoying at times, I guess. Anyway, I would really be grateful if someone could help me out on this one.
(By the way, disabling precompiled headers did not work)
Relevant parts of code:
Error 14:
#include "PlayerEntity.h"
PlayerEntity::PlayerEntity(void) {} // This line causes the error
Error 5:
class GameScreen : public BaseScreen
{
public:
...
private:
...
}; // This line causes the error
Error 4:
private:
std::vector<BaseEntity*> _EntityList; // This line causes the error
Whole PlayerEntity.h file:
#ifndef PENTITY_H
#define PENTITY_H
#include "BaseEntity.h"
class PlayerEntity : public BaseEntity
{
public:
PlayerEntity(void);
PlayerEntity(float, float);
virtual ~PlayerEntity(void);
void render(sf::RenderWindow&);
void update();
private:
void init();
};
#endif
Whole GameScreen.h file:
#ifndef GSCREEN_H
#define GSCREEN_H
#include "BaseScreen.h"
#include "BaseEntity.h"
#include "PlayerEntity.h"
class GameScreen : public BaseScreen
{
public:
GameScreen(sf::Vector2u&);
virtual ~GameScreen(void);
void start();
void stop();
void render(sf::RenderWindow&);
void update(void);
void addEntity(BaseEntity*);
void destoryEntity(int id);
private:
std::vector<BaseEntity*> _EntityList;
sf::Vector2u _ScreenDimensions;
};
#endif
Whole BaseEntity.h file:
#ifndef BSENTITY_H
#define BSENTITY_H
#include "Input.h"
#include <SFML/Graphics.hpp>
class BaseEntity
{
public:
BaseEntity(void);
virtual ~BaseEntity(void);
sf::Vector2f position;
virtual void update(void);
virtual void render(sf::RenderWindow&);
void compare(BaseEntity*);
protected:
sf::Texture *_EntityTexture;
sf::Sprite _EntitySprite;
bool _isAlive;
int _id;
virtual void init();
};
#endif
Whole Input.h file:
#ifndef INPUT_H
#define INPUT_H
#include "ScreenSystem.h"
#include <SFML/Window.hpp>
class Input
{
public:
Input(void);
Input(sf::RenderWindow*);
virtual ~Input(void);
static bool keyPressed(int);
static bool keyReleased(int);
static bool mouseHeld(int);
static bool mouseReleased(int);
private:
static sf::RenderWindow *_Window;
};
#endif
Whole ScreenSystem.h file:
#ifndef GHANDLER_H
#define GHANDLER_H
#include "BaseScreen.h"
#include "MenuScreen.h"
#include "GameScreen.h"
#include <SFML/Window.hpp>
class ScreenSystem
{
public:
ScreenSystem(void);
ScreenSystem(sf::RenderWindow*);
virtual ~ScreenSystem(void);
BaseScreen *getCurrentScreen(void);
void setScreen(int);
private:
int _currentScreenID;
std::vector<BaseScreen*> _Screens;
sf::RenderWindow *_Window;
};
#endif
You have a circular dependency in your headers. BaseEntity.h includes Input.h, which includes ScreenSystem.h, which includes GameScreen.h, which in turn re-includes BaseEntity.h. This leads to class names appearing before they are declared, causing compilation failure.
To avoid this, do not include headers unnecessarily. For example, do not include Input.h from BaseEntity.h, since it's not needed at all; and do not include BaseScreen.h from ScreenSystem.h since only a declaration class BaseScreen; is needed, not the complete class definition.
Also, check that you do not have duplicate header guards. Some of them do not match the header name (e.g. GHANDLER_H for ScreenSystem.h), which makes me think that they may have been accidentally copied from other headers. Finally, don't use reserved names like _EntitySprite for your own symbols; for simplicity, avoid leading or double underscores.
Did you copy the error messages into your question or did you retype them? Because error 14 has 'Class' with a capital C which is almost certainly not right.
Also, you should use as few include directives in your header files as possible. For example, GameScreen doesn't use PlayerEntity, so you can remove that include and BaseEntity is only used via pointer so you can replace
#include "BaseEntity.h"
with a forward declaration
class BaseEntity;
I have a State class that is fully implemented as outlined below. I also have a PlayState class that inherits the State class, it too is fully implemented. My compile error is "playstate.h(6): error C2504: 'State' : base class undefined"
I have checked their order in Global.h, State.h appears before PlayState.h
CODE:
STATE.H
#pragma once
#include "Global.h"
class State
{
public:
State(void);
virtual ~State(void);
virtual void Input(INPUTDATA* InputData);
virtual void Logic(OBJECT go[], INPUTDATA* InputData);
virtual void Render(OBJECT go[]);
virtual void InitGame(OBJECT go[]);
virtual void LoadGraphics(void);
void Toggle();
bool IsEnabled();
private:
bool isEnabled;
};
PlayState.h
#include "Global.h"
class PlayState : public State
{
private:
#define UPDATESPEED 1000 // milliseconds between each update
// global variables
float camXAngle;
float camYAngle;
float camZoom;
int updatetime;
bool gameover;
float runspeed;
D3DLIGHT9 light;
SPRITE graphics;
SPRITE particleTexture;
MODEL terrain[2];
MODEL sky;
public:
PlayState();
~PlayState();
void Input(INPUTDATA* InputData);
void Logic(OBJECT go[], INPUTDATA* InputData);
void Render(OBJECT go[]);
void InitGame(OBJECT go[]);
void LoadGraphics(void);
};
Thanks
If some *.cpp includes "State.h" without "Global.h" somewhere before it then you will have the error that you've posted.
Because when "State.h" includes "Global.h" then "Global.h" does not include "State.h" (because of #pragma once) but it includes "PlayState.h" so in the end you have "PlayState.h" included before class State is defined.
Just don't make such weird circular inclusions.
If your Global.h already includes State.h and PlayState.h and in the order that State.h is placed before PlayState.h, then there is no reason to get the particular error(for the source code you have posted), unless except you are making some silly typo like missing a caps in State. Please check for typos! or there might be another reason to the problem.
You are building a circular dependency of includes, which should be avoided.
A simple solution might be to not include both includes, State.h and PlayState.h in Global.h.
Just include State.h inside PlayState.h and it should be fine. Global.h wont build up any circular dependencies that way.
#pragma once
#include "Global.h"
class PlayState : public State
What is "State"? That is what the compiler is complaining about.
You can't inherit from a class that has not been fully defined. Looking at the file PlayState.h, nowhere do you specify the State class.
CORRECTED CODE:
#pragma once
#include "State.h"
class PlayState : public State