I'm a game designer coming from a Basic-like programming language and moving to C++.
For a new game I'd like to have a gui programmed using OOP.
My gui currently consists of a gui-class (the outer wrapper), a g_element-class (the middle wrapper containing all the common attributes) and a button-class (overriding and extending the g_element-class).
The problem is I'm getting the following error:
Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol "public: static class
std::list,class std::allocator > > gui
::el_stack"(?el_stack#?$gui#V?$g_element#Vbutton######2V?$list#V?$g_element#Vbutton####V?$allocator#V?$g_element#Vbutton#####std###std##A)
I really think that this error is not the only problem - I might have a completely wrong approach for this whole thing. I'm also not really sure about that template-thing - I thought I'd be able to expand my g_element-class with gui-elements later (i.e. buttons, sliders, windows...) - but give me a hint if there's something that I can optimise.
Here is my gui.cpp file (so far):
using namespace std;
template <class GUI_ELEMENT> class gui {
protected:
void add_to_stack(GUI_ELEMENT elem) {
// The error comes from here..
// I wanted a list of all my g_elements (buttons)
el_stack.push_back(elem);
printf("size now: %d", el_stack.size());
}
unsigned int get_stack_size() {
return el_stack.size();
}
public:
static list<GUI_ELEMENT> el_stack; // The elements list
void render() {
// here, I'd like to iterate over all i.e. buttons to draw them
}
};
template <class GUI_ELEMENT> class g_element : public gui<g_element<GUI_ELEMENT> >{
private:
float x;
float y;
float w;
float h;
public:
void set_width(float width) {
this->w = width;
}
float get_width() {
return this->w;
}
};
class button : public g_element<button> {
protected:
char* caption;
public:
button(float x, float y, float w, float h, char* caption) {
this->set_width(w);
this->set_caption(caption);
this->add_to_stack(*this);
}
void set_caption(char* caption) {
this->caption = caption;
}
char* get_caption() {
return this->caption;
}
};
I'd like to use my gui like so:
// Create a few test buttons
button b1(50, 50, 100, 50, "Test");
b1.set_width(150);
float s = b1.get_width();
printf("size w: %f", s);
printf("\ncaption: %s", b1.get_caption());
button b2(50, 50, 100, 50, "Test");
button b3(50, 50, 100, 50, "Test2");
button b4(50, 50, 100, 50, "Test3");
// Rendering currently (all buttons at once)
gui<button> G;
G.render();
// but this would be nicer:
gui::render_buttons()
// or
gui<button>::render()
Is there somebody who might help me? Really big thanks in advance!
All static fields should be defined outside of the class definition. In your case you have to add these lines of code after a class definition:
template<class GUI_ELEMENT>
list<GUI_ELEMENT> gui<GUI_ELEMENT>::el_stack;
Related
I am using an SFML view integrated inside a wxWidgets frame. I used the code sample on the SFML website (which is quite old but I got it to work making a few tweaks) to do this. And then started fleshing out my project from that base class. However, I am at the stage now where I need to create and delete many SFML+wxWidgets windows based on user actions, however SFML crashes whenever I close its parent wxWidgets window.
I get the following error:
Cannot close SFML area when SFML is integrated in a NSView.
All the SFML+wxWidgets examples on the web I found face this error when I run it after closing. This error should not be an issue if the user only needs to close the window once, but I am managing many windows over the user session, so if it crashes once, it brings down the whole app with it.
Here is the section of the header file code for the base class combining wxWidgets and sfml, everything else is specific to my app, and not to the error:
class ChessWidgetBase : public wxControl, public sf::RenderWindow {
public:
ChessWidgetBase(wxWindow* parent, wxSize size);
virtual ~ChessWidgetBase() {};
private:
DECLARE_EVENT_TABLE()
virtual void HandleLeftDown(wxMouseEvent&) {}
virtual void HandleLeftUp(wxMouseEvent&) {}
virtual void OnUpdate() {};
void OnIdle(wxIdleEvent&);
void OnPaint(wxPaintEvent&);
void OnEraseBackground(wxEraseEvent&);
};
This code is based off this minimum reproducable example I used from the internet to make the above class:
#include <iostream>
#include <wx/wx.h>
#include <memory>
#include <SFML/Graphics.hpp>
#ifdef __WXGTK__
#include <gdk/gdkx.h>
#include <gtk/gtk.h>
#endif
using namespace std;
static const int kDefaultWindowWidth = 1280;
static const int kDefaultWindowHeight = 720;
static const int kCanvasMargin = 50;
struct wxSfmlCanvas : public wxControl, public sf::RenderWindow
{
wxSfmlCanvas(
wxWindow *parent = nullptr,
wxWindowID windowId = -1,
const wxPoint &position = wxDefaultPosition,
const wxSize &size = wxDefaultSize,
long style = 0) :
wxControl(parent, windowId, position, size, style)
{
createRenderWindow();
}
virtual void onUpdate(){};
void onIdle(wxIdleEvent& event)
{
// Send a paint message when control is idle, to ensure max framerate
Refresh();
}
void onPaint(wxPaintEvent& event)
{
wxPaintDC dc(this); // Prepare control to be repainted
onUpdate(); // Tick update
display(); // Draw
}
// Explicitly overriding prevents wxWidgets from drawing, which could result in flicker
void onEraseBackground(wxEraseEvent& event){}
void createRenderWindow()
{
#ifdef __WXGTK__
gtk_widget_realize(m_wxwindow);
gtk_widget_set_double_buffered(m_wxwindow, false);
GdkWindow *gdkWindow = gtk_widget_get_window((GtkWidget*)GetHandle());
XFlush(GDK_WINDOW_XDISPLAY(gdkWindow));
sf::RenderWindow::create(GDK_WINDOW_XWINDOW(gdkWindow));
#else
sf::RenderWindow::create(GetHandle());
#endif
}
void setwxWindowSize(const wxSize& size)
{
this->SetSize(size);
}
void setRenderWindowSize(const sf::Vector2u& size)
{
this->setSize(size);
}
virtual ~wxSfmlCanvas(){};
wxDECLARE_EVENT_TABLE();
};
struct Canvas : public wxSfmlCanvas
{
Canvas(
wxWindow* parent,
wxWindowID id,
wxPoint position,
wxSize size,
long style = 0) :
wxSfmlCanvas(parent, id, position, size, style)
{
}
virtual void onUpdate()
{
clear(sf::Color::Yellow);
// TODO: Do some sprite drawing or whatever
}
void onResize(wxSizeEvent& event)
{
auto size = event.GetSize();
auto newCanvasWidth = size.x - (2 * kCanvasMargin);
auto newCanvasHeight = size.y - (2 * kCanvasMargin);
// Resize Canvas window
this->setwxWindowSize({newCanvasWidth, newCanvasHeight});
this->setRenderWindowSize({(unsigned int)newCanvasWidth, (unsigned int)newCanvasHeight});
}
};
struct AppFrame : public wxFrame
{
AppFrame(const wxString& title, const wxPoint& pos, const wxSize& size) :
wxFrame(NULL, wxID_ANY, title, pos, size),
_panel(new wxPanel(this)),
_canvas(new Canvas(
_panel.get(),
wxID_ANY,
wxPoint(kCanvasMargin, kCanvasMargin),
wxSize(kDefaultWindowWidth - (2 * kCanvasMargin), kDefaultWindowHeight - (2 * kCanvasMargin))
))
{
_panel->SetBackgroundColour(*wxCYAN);
////////////////////////////////////////////////////////////////////////////////
// Probably due to some RTTI, IDE is getting confused by this dynamic call
// and doesn't understand the correct Bind overload. Causes non sequitur errors
// to display in the inspector. Suppress.
//
// Dynamic binding is cleanest here, since we don't want to hook up our resize
// handler until our dependencies (Canvas namely) have finished their initialization
////////////////////////////////////////////////////////////////////////////////
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wint-conversion"
Bind(wxEVT_SIZE, &AppFrame::onResize, this);
#pragma clang diagnostic pop
////////////////////////////////////////////////////////////////////////////////
}
void onResize(wxSizeEvent& event)
{
_canvas->onResize(event);
event.Skip();
}
unique_ptr<wxPanel> _panel;
unique_ptr<Canvas> _canvas;
};
struct App : public wxApp
{
virtual bool OnInit()
{
auto frame = new AppFrame("SFML Canvas Demo", wxPoint(100, 100),
wxSize(kDefaultWindowWidth, kDefaultWindowHeight));
frame->Show(true);
return true;
}
};
wxBEGIN_EVENT_TABLE(wxSfmlCanvas, wxControl)
EVT_IDLE(wxSfmlCanvas::onIdle)
EVT_PAINT(wxSfmlCanvas::onPaint)
EVT_ERASE_BACKGROUND(wxSfmlCanvas::onEraseBackground)
wxEND_EVENT_TABLE()
wxIMPLEMENT_APP(App);
(if you want to run it you might have to install sfml+wxwidgets)
Any ways to handle closing a window that prevents a crash with wxWidgets+SFML? Just need some ideas and a couple lines of code to show them, no need for complete examples...
To fix this error upgrade SFML to version >= 2.6.0. You cannot find this in the downloads site for SFML as it hasn't been released yet, so you must install from the Github directly over here and build it from source: https://github.com/SFML/SFML/tree/2.6.x.
The problem says:
Define a class Arc, which draws a part of an ellipse. Hint: fl_arc().
Ellipse is predefined class which draws an ellipse on the window by a statement, e.g., Ellipse e1(Point(200,200),50,50);
and fl_arc() is part of FLTK which I've previously installed it on my Windows machine.
Since the problem has wanted to draw a part of an ellipse by creating a new class named Arc, I think I should make a new class with that name and also use the definition of the class Ellipse and modify it so that it shows a part of an ellipse instead of whole of an ellipse as wanted. This problem is in Programming Principle and practice using C++ book and the only definition that I found in that book about the Ellipse class was this:
struct Ellipse :Shape {
Ellipse(Point p, int w, int h); //center, max and min distance from center
void draw_lines()const;
Point center()const;
Point focus1()const;
Point focus2()const;
void set_major(int ww) {w=ww;}
int major() const {return w;}
void set_minor(int hh) {h=hh;}
int minor() const {return h;}
private:
int w;
int h;
};
and also I found a case of using the fl_arc() in the book which was used for drawing a Circle like this:
fl_arc(point(0).x,point(0).y,r+r,r+r,0,360);
Here r is radius.
So on my think, I changed the parameters of the fl_arc() and wrote the bellow code to give me what the problem has wanted:
#include <Simple_window.h>
struct arc : Shape {
arc(Point p, int w, int h) // center, min, and max distance from center
: w(w), h(h)
{
add(Point(p.x-w,p.y-h));
}
void draw_lines() const {fl_arc(point(0).x,point(0).y,w+w,h+h,0,120);}
Point center() const { return Point(point(0).x+w,point(0).y+h); }
Point focus1() const { return Point(center().x+int(sqrt(double(w*w-h*h))),center().y); }
Point focus2() const { return Point(center().x-int(sqrt(double(w*w-h*h))),center().y); }
void set_major(int ww) { w=ww; }
int major() const { return w; }
void set_minor(int hh) { h=hh; }
int minor() const { return h; }
private:
int w;
int h;
};
int main()
{
using namespace Graph_lib;
Point t(100,100);
Simple_window win(t,600,400, "semi-ellipse");
arc a(Point(200,200),150,50);
a.draw_lines();
win.wait_for_button();
}
The code runs successfully fortunately but it doesn't show any part of an ellipse.
Question:
Does anyone know why?
PS: If we can find some way for modifying a class we can tell that new class to does some new work for us.
Here is one possible implementation, where you use the already existing facilities of class Ellipse, overwriting the function draw_lines(), to define the class Arc:
#include"Simple_window.h"
#include"Graph.h"
#include<iostream>
using namespace Graph_lib;
//---------------------------------------------------------------------------
//Class Arc
namespace Graph_lib{
class Arc : public Ellipse {
public:
Arc(Point p, int w, int h, int arc_n, int arc_x) : Ellipse(p,w,h), arc_min(arc_n), arc_max(arc_x) {}
void draw_lines() const;
private:
int arc_min;
int arc_max;
};
void Arc::draw_lines() const
{
if(color().visibility())
fl_arc(point(0).x,point(0).y, major()*2, minor()*2, arc_min, arc_max);
}
}
//---------------------------------------------------------------------------
int main()
try
{
Simple_window win(Point(100,100), 800, 600, "Exercise #1");
Graph_lib::Arc arc1(Point(100,100),50,50,0,90);
win.attach(arc1);
win.wait_for_button();
}
catch(exception& e)
{
std::cout << e.what() << std::endl;
return 1;
}
catch(...)
{
std::cout << "unknown error..." << std::endl;
return 2;
}
Programming - Principles and Practice Using C++ (pg.477, exercise 1)
solution by Francisco Tavares
Although I could to find the bug of that code but still I have some issues about that exercise that I like to mention them among you professional guys.
If the line a.draw_lines(); will be replaced by this line win.attach(a); the problem runs successfully.
The remained problems are these:
1- Now when I use the name "Arc" instead of the "arc" in above code I get this error.
Error 8 error C2146: syntax error : missing ';' before identifier 'a' c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 25
Error 10
error C3861: 'a': identifier not found c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 25
2- The problem has wanted us to define a class (not a struct) so when I replace struct with class and put keyword public just after class arc : Shape {, I get this error.
*Error 8 error C2243: 'type cast' : conversion from 'arc *' to 'Graph_lib::Shape &' exists, but is inaccessible c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 29
Error 9 error C2243: 'type cast' : conversion from 'arc ' to 'Graph_lib::Shape &' exists, but is inaccessible c:\users\cs\documents\visual studio 2012\projects\test2\test2\test2.cpp 30
Any idea?
I have incorporated polymorphism with a single subclass for now. Two of these functions, as seen in the following code, Draw() and SetValue(int,int,int) are causing linker errors.
#include "Header.h"
class Object{
int tag;
public:
void SetValues(int,int,int);
void Draw();
int getTag(){
return tag;
}
};
class Square: public Object{
int red;
int green;
int blue;
void Draw();
void SetValues(int red2,int green2, int blue2){
red=red2;
green=green2;
blue=blue2;
}
};
void Square::Draw(){
// Draws a square with a gradient color at coordinates 0, 10
glBegin(GL_QUADS);
{
glColor3f(red, green, blue);
glVertex2i(1, 11);
glColor3f(red * .8, green * .8, blue * .8);
glVertex2i(-1, 11);
glColor3f(red * .5, green * .5, blue * .5);
glVertex2i(-1, 9);
glColor3f(red * .8, green * .8, blue * .8);
glVertex2i(1, 9);
}
glEnd();
}
The errors
Error 1 error LNK2019: unresolved external symbol "public: void __cdecl Object::SetValues(int,int,int)" (?SetValues#Object##QEAAXHHH#Z) referenced in function "public: void __cdecl State::DrawAll(void)" (?DrawAll#State##QEAAXXZ) C:\Users\Asher\documents\visual studio 2012\Projects\Procedural Terrain\Procedural Terrain\State.obj Procedural Terrain
Error 2 error LNK2019: unresolved external symbol "public: void __cdecl Object::Draw(void)" (?Draw#Object##QEAAXXZ) referenced in function "public: void __cdecl State::DrawAll(void)" (?DrawAll#State##QEAAXXZ) C:\Users\Asher\documents\visual studio 2012\Projects\Procedural Terrain\Procedural Terrain\State.obj Procedural Terrain
In a larger class, which does no inherit Object's functions, uses DrawAll() with a Draw() call in it.
The cpp file and the two respective header files are as follows.
#include "Header.h"
#include "Object.h"
float rotate_z=0;
class State{
private:
std::vector<Object> storage;
public:
State();
State Interpolate(State, State, double);
void Integrate(State,double, const double);
void DrawAll();
void AddObject(Object);
void RemoveObject(int);
};
State::State(){
}
State State::Interpolate(State current,State previous,const double alpha){
//current*alpha + previous * ( 1.0 - alpha );
return current;
}
void State::Integrate(State current, double t, const double dt){
}
void State::AddObject(Object object){
storage.push_back(object);
}
void State::RemoveObject(int tag){
//for(int i=0;i<storage.size;i++){
// if(storage.at(i).getTag==tag){
//storage.erase(storage.begin()+i);
// }
//}
}
void State::DrawAll(void)
{
// reset view matrix
glLoadIdentity();
// move view back a bit
glTranslatef(0, 0, -30);
// apply the current rotation
glRotatef(rotate_z, 0, 0, 1);
rotate_z += 5;
// by repeatedly rotating the view matrix during drawing, the
// squares end up in a circle
int i = 0, squares = 15;
float red = 0, blue = 1;
for (; i < squares; ++i){
Square square;
Object * squareP=□
glRotatef(360.0/squares, 0, 0, 1);
// colors change for each square
red += 1.0/12;
blue -= 1.0/12;
squareP->SetValues(red,0.6,blue);
squareP->Draw();
}
}
The Object header -
#ifndef Object_H
#define Object_H
class Object{
int tag;
public:
void SetValues(int,int,int);
void Draw();
int getTag();
};
class Square: public Object{
int red;
int green;
int blue;
void Draw();
void SetValues(int red2,int green2, int blue2);
};
#endif
Lastly the State header -
#ifndef State_H
#define State_H
#include "Object.h"
#include <vector>
class State{
private:
std::vector<Object> storage;
public:
State();
State Interpolate(State, State, double);
void Integrate(State,double, const double);
void DrawAll();
void AddObject(Object);
void RemoveObject(int);
};
#endif
This is the first C++ project I have worked on and have not fully transferred from a Java background. What could the problem be?
Your Object class has no implementation of SetValues function. You may want a pure virtual function. Same for Draw.
class Object {
virtual void SetValues(int,int,int) = 0;
}
Also note that in C++ functions are not virtual by default. You have to use the virtual keyword explicitly in the base class.
Also class Object seems to be defined at multiple places. Why? Defining it in Object.h would be sufficient.
Also please indent your code because it is very hard to read.
Also std::vector<Object> will not do what you want! Unline Java, where everything is a reference, in C++ things are stored by value in an std::vector and therefore your code is subject to the slicing problem. You want to use at lease a pointer there (std::vector<Object*>) but a smart pointer would be even better (std::vector<std::shared_ptr<Object>>)
Nothing is marked as virtual, and I can't see any implementation for Object::Draw() or Object::SetValues().
In C++ to allow a subclass to override a function in the base class, it needs to be marked as virtual (in Java everything is always "virtual").
You can have "abstract" methods (like Java) by saying
class Object {
public:
virtual void SetValues(int,int,int) = 0;
Here is the relevant code:
Canvas.cpp
#ifndef CANVAS
#define CANVAS
#include "graphicsDatatypes.h"
class Canvas
{
private:
// Current and next points to draw to
struct cartesianPoint currentPoint, nextPoint;
public:
Canvas::Canvas() { numLinesDrawn = 0; };
Canvas::~Canvas();
struct cartesianPoint getCurrentPoint() { return currentPoint; };
void setCurrentPoint(int x, int y)
{
currentPoint.x = x;
currentPoint.y = y;
}
};
#endif
main.cpp
#include "glut-3.7.6-bin\glut.h"
#include "Canvas.cpp"
// Window size
int winWidth, winHeight;
// User's drawing space - current maximum of 4000 lines
Canvas userDrawSpace();
void callbackMouse(int button, int state, int x, int y)
{
userDrawSpace.setCurrentPoint(x, y);
}
The error I am getting is - error C2228: left of '.setCurrentPoint' must have class/struct/union
Any idea why? The class is pretty clearly defined, and include should simply be bringing in the text. Visual studios recognizes that Canvas is a class when I hover over it with my mouse, so I have no clue what's going on. Any help is appreciated, thanks.
The line
Canvas userDrawSpace();
looks like it should be creating Canvas object, but in fact it declares a function called userDrawSpace returning a Canvas object :-(.
That's a very common gotcha in C++.
Just get rid of the () and it should be ok.
I am trying to create a generic menu button class that is templated to a class, so I can make this button in any class. I want to create a void function pointer to different functions in that class, so when you click on the New Game button, it will call the NewGame() function etc.
I'm still a little new to the idea of creating function pointers and would like some advice.
I get a crazy link error everytime I try to compile my code now with this Menubutton.
here is the error:
Error 1 error LNK2019: unresolved
external symbol "public: void
__thiscall MENUBUTTON::Draw(void)"
(?Draw#?$MENUBUTTON#VTitleScreen####QAEXXZ)
referenced in function "public:
virtual void __thiscall
TitleScreen::Draw(void)"
(?Draw#TitleScreen##UAEXXZ) TitleScreen.obj
MenuButton.h
template <class t>
struct MENUBUTTON
{
SPRITE Normal; // Sprite to display when not hovered over or pressed down
SPRITE Hover; // Sprite to display when hovered over
RECTANGLE HoverBounds; // The Rectangle that activates the hover flag
t* pClass; // Pointer to the templated class
void (t::*ClickFunction)(); // Pointer to void function
void SetButton(int xPos, int yPos, int width, int height, int hPadLeft, int hPadTop, int hWidth, int hHeight, LPCTSTR normalFilePath, LPCTSTR hoverFilePath, t* objectClass, void (t::*ClickFunction)());
bool IsMouseHover();
void CheckPressed();
void Draw();
};
MenuButton.cpp
#include "Global.h"
template <class t>
void MENUBUTTON<t>::SetButton(int xPos, int yPos, int width, int height, int hPadLeft, int hPadTop, int hWidth, int hHeight, LPCTSTR normalFilePath, LPCTSTR hoverFilePath, t* objectClass, void (t::*ClickFunction)())
{
// Position
Hover.position.x = Normal.position.x = xPos;
Hover.position.y = Normal.position.y = yPos;
Hover.position.z = Normal.position.z = 0;
// Width / Height
Hover.width = Normal.width = width;
Hover.height = Normal.height = height;
// Hover RECTANGLE
HoverBounds.x = xPos + hPadLeft;
HoverBounds.y = yPos + hPadTop;
HoverBounds.width = hWidth;
HoverBounds.height = hHeight;
// Load the Sprites
LoadSprite(&Normal, normalFilePath, width, height, 1, 1);
LoadSprite(&Hover, hoverFilePath, width, height, 1, 1);
// Set the Click function pointer
this->pClass = objectClass;
this->ClickFunction = ClickFunction;
}
template <class t>
void MENUBUTTON<t>::Draw()
{
if(IsMouseHover())
{
DrawSprite(&Hover, 0, Hover.position.x, Hover.position.y, Hover.position.z);
}
else
{
DrawSprite(&Normal, 0, Normal.position.x, Normal.position.y, Normal.position.z);
}
}
template <class t>
bool MENUBUTTON<t>::IsMouseHover()
{
return (((InputData.MousePosition.x >= HoverBounds.x) && (InputData.MousePosition.x <= (HoverBounds.x + HoverBounds.width))) &&
((InputData.MousePosition.y >= HoverBounds.y) && (InputData.MousePosition.y <= (HoverBounds.y + HoverBounds.height)))) ? true : false;
}
Here is my Title Screen which is using the menu button.
TitleScreen.h
class TitleScreen : public BaseState
{
// SPRITES
SPRITE titleScreenBG;
// MENU BUTTONS
MENUBUTTON<TitleScreen> playButton;
MENUBUTTON<TitleScreen> quitButton;
public:
TitleScreen();
virtual void Initialize();
virtual void End();
virtual void Update(float dt, INPUTDATA* input);
virtual void Draw();
void QuitGame();
void NewGame();
};
TitleScreen.cpp
#include "Global.h"
// Constructors
TitleScreen::TitleScreen()
{
}
// Virtual Voids
void TitleScreen::End()
{
}
void TitleScreen::Initialize()
{
this->Enabled = true;
this->Visible = true;
// Initialize sprites
ZeroMemory(&titleScreenBG, sizeof(SPRITE));
LoadSprite(&titleScreenBG, TEXT("../../PNG/TitleScreenBG.png"), 1440, 900, 1, 1);
titleScreenBG.position.x = titleScreenBG.position.y = titleScreenBG.position.z = 0;
// Initialize buttons
ZeroMemory(&playButton, sizeof(MENUBUTTON<TitleScreen>));
playButton.SetButton(55, 170, // x , y
512, 128, // width, height
10, 10, // Left, Top Padding
400, 70, // Hover width, Hover height
TEXT("../../PNG/NewGame.png"), TEXT("../../PNG/NewGameH.png"),
this, &TitleScreen::NewGame);
ZeroMemory(&quitButton, sizeof(MENUBUTTON<TitleScreen>));
quitButton.SetButton(55, 240, // x , y
512, 128, // width, height
10, 10, // Left, Top Padding
190, 70, // Hover width, Hover height
TEXT("../../PNG/QuitButton.png"), TEXT("../../PNG/QuitButtonH.png"),
this, &TitleScreen::QuitGame);
}
void TitleScreen::Update(float dt, INPUTDATA* input)
{
}
void TitleScreen::Draw()
{
StartRender();
DrawSprite(&titleScreenBG, 0, titleScreenBG.position.x, titleScreenBG.position.y, titleScreenBG.position.z);
playButton.Draw();
quitButton.Draw();
EndRender();
}
// Public Methods
void TitleScreen::QuitGame()
{
CloseDirect3D();
}
void TitleScreen::NewGame()
{
CloseDirect3D();
}
If anyone has any advice on how I can make the buttons dynamic for any case in a different way, or know what this problem is, please help! :)
To get rid of the link error, move all method definitions starting with template from the .cpp file to the .h file. In your code, move these:
template <class t> void MENUBUTTON<t>::SetButton ... { ... }
template <class t> void MENUBUTTON<t>::Draw ... { ... }
The reason why it doesn't work with the .cpp file is that the compiler treats MENUBUTTON<Foo> and MENUBUTTON<Bar> etc. as different classes, and it generates and compiles such a class whenever it is used. So if you use MENUBUTTON<TitleScreen> when compiling titlescreen.cpp, then the MENUBUTTON<TitleScreen> code will be compiled into the object file titlescreen.o. But the methods SetButton and Draw will be missing at link time, because they are not defined in titlescreen.cpp or any of the .h files it includes. MenuButton.o won't contain it either, because MenuButton.cpp does not need MENUBUTTON<TitleScreen>.
Just to clarify the first answer, you can't have a template class that is declared in a header and then implemented in a separated compiled translation unit (i.e. .cpp file). You've got to put all the code in the header. You can either put it all in the initial class declaration, or using "inline" declare the class first with the functions, then implement the specific functions further down in the header.
Speaking of a better way ... why do you need a template here?
Plain old virtual function or pointer to member would do.
This would be a perfect application of the Command Design Pattern.
Templates give you compile-time polymorphism, while you are probably looking for run-time polymorphism here.