LNK2019 Error in C++ class definition Example needed [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you get a minimal SDL program to compile and link in visual studio 2008 express?
So I am new to C++ and need to create a class. I think this has something to do with the implementation of the methods in the Sprite.cpp.
Can someone give me an example of a simple class with properties and a method. Or at least let me know what I am doing wrong?
Error #1
Error 12 error LNK2019: unresolved external symbol __imp___CrtDbgReportW referenced in function "public: void __thiscall std::_String_const_iterator<char,struct std::char_traits<char>,class std::allocator<char> >::_Compat(class std::_String_const_iterator<char,struct std::char_traits<char>,class std::allocator<char> > const &)const " (?_Compat#?$_String_const_iterator#DU?$char_traits#D#std##V?$allocator#D#2##std##QBEXABV12##Z) D:\GSE\Game with Jon Bye\game\game\main.obj
Error #2
Error 13 error LNK1120: 1 unresolved externals D:\GSE\Game with Jon Bye\game\Debug\game.exe 1
Sprite.h
#include <string>
#include <SDL.h>
#include "Functions.h"
using namespace std;
class Sprite
{
private:
int PosX;
int PosY;
int xDist;
int yDist;
string ImagePath;
SDL_Surface Screen;
SDL_Surface *temp, *sprite, *screen;
public:
Sprite(int PosX, int PosY, string ImagePath, SDL_Surface Screen );
void Sprite::DrawSprite( int x, int y, SDL_Surface *sprite, SDL_Surface *screen )
{
//Make a temporary rectangle to hold the offsets
SDL_Rect offset;
//Give the offsets to the rectangle
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface( sprite, NULL, screen, &offset );
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
void Sprite::Draw()
{
#pragma region Char to String Conversion
string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';
#pragma endregion
temp = SDL_LoadBMP(writable);
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
// free the string after using it
delete[] writable;
DrawSprite(PosX, PosY, sprite, screen);
}
void Sprite::Move(int xDist, int yDist)
{
PosX += xDist;
PosY += yDist;
Draw();
};
};
Sprite.cpp
#include "Sprite.h"
Sprite::Sprite(int posX, int posY, std::string imagePath, SDL_Surface screen) : PosX(posX), PosY(posY), ImagePath(imagePath), Screen(screen)
{
void DrawSprite( int x, int y, SDL_Surface *sprite, SDL_Surface *screen );
void Draw();
void Move(int xDist, int yDist);
}

Ah my buddy Jonathan O! Looks like you took my advice to use SDL after all...
I'm not sure what your error means, but I know that in SDL, you need to put this:
#undef main
After your:
#include <SDL.h>
Or else it will not work. Why? For some reason SDL defines "main" somewhere, so the linker freaks out when you include "SDL.h", and gets all confused (since main is the entry function).
Perhaps this is the source of your error, although I doubt it, the error message looks like it has something to do with strings...
Also, I don't really get what's going on in your Sprite.CPP file. If you're still new to C++ and looking at how to create classes in C++, you'll find some C++ tutorials here, it's how I started learning C++: http://thenewboston.org/list.php?cat=16

Unresolved externals in C++ when using vectors and find
I was in debug mode and not release mode.
Make sure you set up the linker settings etc in the new Release mode that you have selected and that you are building the Release project.

Related

Why the rendered squares duplicate?

My problem is that when i run programm it runs normally for around 10-20 seconds, and then it glitch out. You can see further what's happening on the video.
https://youtu.be/YOlhjQFTzZc
This error is hunting me for over a month, First i thought this was some mistake in making shorter Render function. But not.
You can see it here.
void Render(char * image_place, int object_x, int object_y)
{
SDL_Surface * object_image = IMG_Load(image_place);
SDL_Rect object_position;
object_position.x=object_x;
object_position.y=object_y;
SDL_BlitSurface(object_image, NULL, ekran, &object_position);
}
But when i started "researching" on this topic more, i discovered that it happen even without using this function!
Here is code from the video:
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
#include <windows.h>
#include <time.h>
using namespace std;
//SDL
SDL_Window * okno;
SDL_Surface * ekran;
SDL_Rect pozycja_obramowki;
SDL_Event zdarzenie;
SDL_Rect tlo_pos;
//zmienne
int x_obraz=0;
int y_obraz=0;
int main(int argc, char*args[])
{
SDL_Init(SDL_INIT_EVERYTHING);
okno = SDL_CreateWindow("LevelEditor",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED, 1280, 720, NULL);
ekran = SDL_GetWindowSurface(okno);
while(true)
{
{//render
SDL_Surface * tlo = IMG_Load("biel.png");
tlo_pos.x=0;
tlo_pos.y=0;
SDL_BlitSurface(tlo,NULL, ekran, &tlo_pos);
SDL_Surface * obramowka = IMG_Load("obramowka.png");
pozycja_obramowki.x=x_obraz;
pozycja_obramowki.y=y_obraz;
SDL_BlitSurface(obramowka,NULL, ekran, &pozycja_obramowki);
}
{//zdarzenia
if(SDL_PollEvent(&zdarzenie))
{
if(zdarzenie.type==SDL_QUIT)
{
return 0;
}
}
}
{//sterowanie
if(GetAsyncKeyState(VK_RIGHT)) {x_obraz=x_obraz+5;}
if(GetAsyncKeyState(VK_LEFT)) {x_obraz=x_obraz-5;}
if(GetAsyncKeyState(VK_UP)) {y_obraz=y_obraz-5;}
if(GetAsyncKeyState(VK_DOWN)) {y_obraz=y_obraz+5;}
}
{//fps end & odswiezanie ekranu
SDL_UpdateWindowSurface(okno);
}
}
}
If i wrote something wrong or explained anything wrong, feel free to comment on this post. Any help will be useful, thanks ; )
You shouldn't call IMG_Load repeatedly. (I suspect that you're running out of memory pretty quickly.)
Load all images at startup and store pointers to the resulting surfaces.
// Moved out of the loop
SDL_Surface * tlo = IMG_Load("biel.png");
SDL_Surface * obramowka = IMG_Load("obramowka.png");
while(true)
{
// As before, but without declaring the variables mentioned above.
}

Error C2659 in C++ Visual Studio

I am new to this and to programming in C++
I keep getting the error Errors: 1 error C2659: '=' : function as left operand W:\CGT 215\Final Project\game\game\paddle.cpp 11 1 game
2 IntelliSense: expression must be a modifiable lvalue w:\CGT 215\Final Project\game\game\paddle.cpp 11 2 game
#include "Paddle.h"
#include <iostream>
Paddle::Paddle(int width, int height, float (*Controller)())
{
m_position.x = 100;
m_position.y = 100;
m_width = width;
m_height = height;
Control = Controller;
}
void Paddle::Update()
{
m_position.y += *Control();
}
Given the error code, as documented here, Control seems to be an existing function and not a function pointer hence cannot be assigned. You want to define another field to hold the function pointer.
Here a code sample to do that:
struct Paddle
{
float (*Control)();
...
Paddle(int width, int height, float (*Controller)());
void Update();
};
Then, your Update implementation should not dereference the Control function pointer:
void Paddle::Update()
{
m_position.y += Control();
}
Your update function may remain unchanged.

vector, sfml and "the value of esp was not properly saved across the function call" error

I have a struct "Layer" and class "LayerHandler". Layer consists only a texture, sprite and two constructors - one default and one with a reference parameter. LayerHandler class is a class that handles the drawing of all the layers we have. I add layers to this class and later I use win.draw(layerhandler_object) to draw everything. LayerHandler inherits from Drawable to do so and it overrides virtual void draw().
LayerHandler.h:
#ifndef LAYERHANDLER_H
#define LAYERHANDLER_H
#include <vector>
#include <SFML\Graphics.hpp>
using namespace std;
using namespace sf;
struct Layer {
Texture tex;
Sprite spr;
Layer() { }
Layer(Layer& l) {
tex = l.tex;
spr = l.spr;
}
};
class LayerHandler : public Drawable {
private:
vector<Layer*> layers;
virtual void draw(RenderTarget& target, RenderStates states) const {
for (int i=0; i<layers.size(); i++)
target.draw(layers[i]->spr, states);
}
public:
LayerHandler();
~LayerHandler();
void Add(Layer& layer);
};
#endif
LayerHandler.cpp:
#include "LayerHandler.h"
LayerHandler::LayerHandler() {
}
LayerHandler::~LayerHandler() {
}
void LayerHandler::Add(Layer& layer) {
layers.push_back(new Layer(layer));
}
and main.cpp:
#include <iostream>
#include <SFML\Graphics.hpp>
#include "LayerHandler.h"
using namespace std;
using namespace sf;
int main() {
RenderWindow win(VideoMode(800, 600), "Raven", Style::Default);
win.setFramerateLimit(60);
win.setVerticalSyncEnabled(true);
win.setMouseCursorVisible(false);
LayerHandler lhandler;
Layer back;
back.tex.loadFromFile("bao/gfx/back.png");
back.spr.setTexture(back.tex);
back.spr.setPosition(0, 50);
lhandler.Add(back);
Event evt;
float dt = 0.f;
Clock clock;
float dwticks = clock.getElapsedTime().asMilliseconds();
float dwnewticks = 0.f;
while (win.isOpen()) {
if (win.pollEvent(evt)) {
if (Keyboard::isKeyPressed(Keyboard::Key::Escape)) {
win.close();
}
} else {
dwnewticks = clock.getElapsedTime().asMilliseconds();
dt = dwnewticks > dwticks ? (dwnewticks - dwticks) / 4000.f : 0.f;
dwticks = dwnewticks;
win.clear();
win.draw(lhandler);
win.display();
}
}
return 0;
}
I think it's not complicated and that I did everything ok, but I get this "The value of ESP was not properly saved across the function call" error. I have no idea why I get this error. I know that it may be caused by mismatched calling conventions, but I don't see anything like that in my code... I've got to say that this is the first time ever I got this error and I'm completely out of ideas how to deal with it. Any help?
Don't know why, but the problem was with SFML libraries. Here I'm using version 2.2 for 32-bit apps. I downloaded version 2.3 32-bit and compiled my app with the new 2.3 libraries and now it works perfect.

C calling a class function inside of another Class that is currently an Object

new here, so be gentle, I'm currently doing my Major Project for my course and, I'm not asking for homework to be done for me, i just can't wrap my head around a strange problem i am having and have not been able to find an answer for it, even on here. I'm using SDL for my Drawing.
I'm doing Object Orientated Programming with my Project or a "state Machine" (which sounds less painful in a newbies mind, believe me), and in the render part of my Class Game1.cpp i am trying to call a Draw Function of my Player Class, but for some unknown reason that i can not fathom, it just skips this function call completely.
I have no errors, i even used breakpoints to find out what was happening, but it just skipped it completely every time, it is drawing the screen black as well without fail. Any help as t why it is skipping this would be really appreciated.
I honestly feel like it's a simple rookie mistake, but any and all scrutiny is welcome of my code, anything i can do to better myself is appreciated.
Game1.cpp:
#include "Game1.h"
#include "PlayerCharacter.h"
Game1::Game1( World * worldObject )
{
//object setup
this->worldObject = worldObject;
setDone (false);
}
Game1::~Game1()
{
}
void Game1::handle_events()
{
//*******************************************
//**//////////////Call Input///////////////**
//*******************************************
//******Check for Keyboard Input*************
//******Check Keyboard Logic*****************
//******Check for Mouse Input****************
//The mouse offsets
x = 0, y = 0;
//If the mouse moved
if (SDL_PollEvent(&worldObject->event))
{
if( worldObject->event.type == SDL_MOUSEMOTION )
{
//Get the mouse offsets
x = worldObject->event.motion.x;
y = worldObject->event.motion.y;
}
}
//******Check Mouse Logic********************
}
void Game1::logic()
{
//*******************************************
//**//////////Collision Detection//////////**
//*******************************************
//******Check Player Bullet Collision Loop***
//Check for collision with enemies
//Check for collision with bitmap mask (walls)
//******Check Enemy Bullet Collision Loop****
//Check for Collision with Player
//Check for collision with bitmap mask (walls)
}
void Game1::render()
{
//*******************************************
//**////////////////Drawing////////////////**
//*******************************************
//******Blit Black Background****************
SDL_FillRect(worldObject->Screen , NULL , 0xff000000);
//******Blit Bitmap Mask*********************
//******Blit Flashlight**********************
//******Blit Map*****************************
//******Blit Pickups*************************
//******Blit Bullets*************************
//******Blit Player**************************
&PlayerCharacter.Draw; // <----- Skips this line completely, no idea why
//******Blit Enemies*************************
//******Blit Blackened Overlay***************
//******Blit HUD*****************************
//******Flip Screen**************************
SDL_Flip(worldObject->Screen);
}
Game1.h
#ifndef __Game1_H_INLUDED__
#define __Game1_H_INLUDED__
#include "GameState.h"
#include "SDL.h"
#include "ImageLoader.h"
using namespace IMGLoader;
class Game1 : public GameState
{
private:
//Menu Image
World * worldObject;
SDL_Rect PauseMenu,Item1Tile,Item2Tile,Item3Tile;
/*bool bPauseMenu, bItem1Tile, bItem2Tile, bItem3Tile;
int ButtonSpace,ButtonSize;
float x,y;
int Alpha1,Alpha2;*/
//Clipping Window
//SDL_Rect sclip,dclip;
public:
//Loads Menu resources
Game1 (World * worldObject);
//Frees Menu resources
~Game1();
//Main loop functions
void handle_events();
void logic();
void render();
};
#endif
PlayerCharacter.cpp
#include "PlayerCharacter.h"
SDL_Rect psclip,pdclip;
PlayerCharacter::PlayerCharacter ( float X, float Y, float dX, float dY, float Angle, float Speed, bool Existance, int Height, int Width, int Health, int Shield, SDL_Surface* Player ):Characters ( X, Y, dX, dY, Angle, Speed, Existance, Height, Width, Health )
{
this->Player = Player;
this->Shield = Shield;
this->Player = load_image("image\Player1.png");
}
void PlayerCharacter::setShield ( int Shield )
{
this->Shield = Shield;
}
int PlayerCharacter::getShield ( void )
{
return Shield;
}
void PlayerCharacter::Draw( )
{
psclip.x = 0; psclip.y = 0; psclip.w = 64; psclip.h = 64;
pdclip.x = 640; pdclip.y = 318; pdclip.w = 64; pdclip.h = 64;
SDL_BlitSurface(Player, &psclip, worldObject->Screen, &pdclip);
}
PlayerCharacter.h
#ifndef __PlayerCharacter_H_INCLUDED__
#define __PlayerCharacter_H_INCLUDED__
#include "Characters.h"
class PlayerCharacter : public Characters
{
private:
int Shield;
SDL_Surface* Player;
World *worldObject;
public:
PlayerCharacter ( float X, float Y, float dX, float dY, float Angle, float Speed, bool Existance, int Height, int Width, int Health, int Shield, SDL_Surface* Player );
void setShield ( int Shield );
int getShield ( void );
void Draw ( );
};
#endif
The line
&PlayerCharacter.Draw; // <----- Skips this line completely, no idea why
is not actually a function call. It's an expression that take the address of the Draw function in the PlayerCharacter class and does nothing with it.
I'm actually kind of surprised it compiles without errors, or at least tons of warnings.
You need to create a PlayerCharacter object, and then call the function in the object.
&PlayerCharacter.Draw is not a function call. PlayerCharacter::Draw() is not a static class method, so you need a PlayerCharacter object to invoke this method on.
You have a class PlayerCharacter, which defines what a PlayerCharacter is and what can be done with it. But as far as I see, you don't have a single PlayerCharacter object, i.e. no player character. If you had one, let's call him pc, then you could draw him with pc.Draw(). For that, you would have to instantiate the class, e.g. via PlayerCharacter pc( ... ), with the ... replaced by some appropriate values for the multitude of constructor parameters you have there. (You really want a default constructor, initializing all those to zero or other appropriate "start" value...)

C++ Variable not being instantiated properly

Sprite1 *test = new Sprite1(450, 450, "enemy.bmp", *screen);
test->DrawJon();
SDL_Delay(1000);
test->MoveJon(20,20);
I am getting a runtime error on line #2. It says access violation at 0x0
Sprite1 is a class I have defined and DrawJon() and MoneJon() in the class. This syntax is ok with the compiler but fails in runtime.
Sprite1.cpp
#include "Sprite1.h"
Sprite1::Sprite1(int posX, int posY, std::string imagePath, SDL_Surface screen) : PosX(posX), PosY(posY), ImagePath(imagePath), Screen(screen)
{
void DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen );
void DrawJon();
void MoveJon(int xDist, int yDist);
}
void Sprite1::DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen )
{
//Make a temporary rectangle to hold the offsets
SDL_Rect offset;
//Give the offsets to the rectangle
offset.x = x;
offset.y = y;
//Blit the surface
SDL_BlitSurface( sprite, NULL, screen, &offset );
SDL_UpdateRect(screen, 0, 0, 0, 0);
}
void Sprite1::DrawJon()
{
#pragma region Char to String Conversion
string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';
#pragma endregion
temp = SDL_LoadBMP(writable);
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
// free the string after using it
delete[] writable;
DrawSprite1Jon(PosX, PosY, sprite, screen);
}
Sprite1.h
#include <string>
#include <SDL.h>
#include "Functions.h"
using namespace std;
class Sprite1
{
private:
int PosX;
int PosY;
int xDist;
int yDist;
string ImagePath;
SDL_Surface Screen;
SDL_Surface *temp, *sprite, *screen;
public:
Sprite1(int PosX, int PosY, string ImagePath, SDL_Surface Screen );
void DrawSprite1Jon( int x, int y, SDL_Surface *sprite, SDL_Surface *screen);
void DrawJon();
void MoveJon(int xDist, int yDist);
};
EDIT:
upon further investigation, it is this line
DrawSprite1Jon(PosX, PosY, sprite, screen);
That is failing in the DrawJon()
At least this piece of your code is broken:
string ImagePath;
char * writable = new char[ImagePath.size() + 1];
copy(ImagePath.begin(), ImagePath.end(), writable);
writable[ImagePath.size()] = '\0';
You are creating local ImagePath variable, not using the class member variable. The local variable shadows the member variable. Remove the local variable (first line in above snippet).
Also, you can probably (I'm not very familiar with SDL) do the loading simply like this:
temp = SDL_LoadBMP(ImagePath.c_str());
Then, just guessing, but image loading might be failing, and that function returns NULL pointer. So check return value and then check the error (either there is some SDL error function you can call, or you need to check standard errno global variable.
Further suggestion: turn on compiler warnings (for gcc: -W -Wall) and learn to understand (copying the warning to google is a good start) and then fix the warnings. Most of the time they are real bugs (hence the warning!) and even when they are not, fixing the warning will make your code better.
I is apparent that you've just began to program in C++, maybe you have a javascript background, therefore you've tried to put function declarations into the constructor. It is a wrong idea here. (#pragma's usually have some explicit meaning, you also misuse them here. see eg. #pragma GCC poison)
I see a lot of confusion in this code.
I suggest, you grab a great quality beginner C++ book, before going ahead with this piece of code. At this point I see no reason trying to hammer-out something reasonable from this code.
There were some problems with my implementation but in the end I had to build in release mode rather than debug mode.