unable to initialize Static const string - c++

I have a class "GameOverState" which has a private member
static const std::string s_gameOverID;
In GameOverState.cpp I am initialising as :
const std::string GameOverState::s_gameOverID = "GAMEOVER";
I am getting the following errors:
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2440: 'initializing' : cannot convert from 'const char [9]' to 'int'
error C2377: 'std::string' : redefinition; typedef cannot be overloaded with any other symbol
error C2373: 's_gameOverID' : redefinition; different type modifiers
error C2143: syntax error : missing ';' before 'GameOverState::s_gameOverID'
I have a PlayState class/PauseState class which have the same implementation which are working fine. How do I fix this bug??
GameOverState.h
#pragma once
#include "GameState.h"
#include "PlayState.h"
#include "MenuState.h"
#include "PauseState.h"
#include "AnimatedGraphic.h"
#include <string>
class GameObject;
class GameOverState : public GameState
{
public:
virtual void update();
virtual void render();
virtual bool onEnter();
virtual bool onExit();
virtual std::string getStateID() const { return s_gameOverID; }
private:
static void s_gameOverToMain();
static void s_restartPlay();
static const std::string s_gameOverID;
std::vector<GameObject*> m_gameObjects;
}
GameOverState.cpp
#include "GameOverState.h"
const std::string GameOverState::s_gameOverID = "GAMEOVER";
void GameOverState::s_gameOverToMain()
{
TheGame::Instance()->getStateMachine()->changeState(new MenuState());
}
void GameOverState::s_restartPlay()
{
TheGame::Instance()->getStateMachine()->changeState(new PlayState());
}
bool GameOverState::onEnter()
{
if (!TheTextureManager::Instance()->load("assets/gameover.png", "gameovertext", TheGame::Instance()->getRenderer()))
{
return false;
}
if (!TheTextureManager::Instance()->load("assets/main.png", "mainbutton", TheGame::Instance()->getRenderer()))
{
return false;
}
if (!TheTextureManager::Instance()->load("assets/restart.png", "restartbutton", TheGame::Instance()->getRenderer()))
{
return false;
}
GameObject* gameOverText = new AnimatedGraphic(new LoaderParams(200, 100, 190, 30, "gameovertext"), 2);
GameObject* button1 = new MenuButton(new LoaderParams(200, 200, 200, 80, "mainbutton"), s_gameOverToMain);
GameObject* button2 = new MenuButton(new LoaderParams(200, 300, 200, 80, "restartbutton"), s_restartPlay);
m_gameObjects.push_back(gameOverText);
m_gameObjects.push_back(button1);
m_gameObjects.push_back(button2);
std::cout << "entering PauseState\n";
return true;
}

You're missing the semicolon after the definition of GameOverState.
The preprocessor runs before compilation and basically just copy pastes the content of the header in the source file, altough we can't see that. An error resulting from a broken header can thus be pretty misleading.
It's legal to have class definitions inside a variable definition and the position of specifiers (like static) is not limited to the beginning of a declaration, either (for example, int const static x = 0; is fine).
So, your code looks like this to the compiler:
class GameOverState {} static const std::string GameOverState::s_gameOverID = "GAMEOVER";
Hopefully the errors make more sense now.

As everyone else has said, you're probably missing the #include line in your header if your other two classes are working fine. It's presuming and expecting an int, so that seems the case.
Make sure #include<string> is in your header

Related

How to pass an enum class which is inside another class's function by reference?

I am still fairly new to C++, so sorry if the code is a bit amateurish, that might be the source of the problem.
I've spent some time searching this site and across the web. There are plenty of examples using enums (not enum class) and also of using enums and enums class outside of classes, but didn't really find anything useful for my particular scenario, see below. Of course, I may have seen the answer, but my C++ is not advanced enough yet to recognize it.
Basically I want to pass 2 "state" enums classes into a method, in a different class from the ones in which the enums classes are defined, and then change the state of the second enum class based on the value in the first enum class. These enum classes are defined inside a class which contains a pointer to the second class in which the method is defined. Class declarations are in header files and defined in separate .cpp files which include the relevant headers. See the detailed code and errors below.
Hoping someone can help me interpret the error messages at the end and figure out how to achieve this.
main.cpp
#include <iostream>
#include "firstfile.h"
int main() {
FirstFile firstobject;
firstobject.Function1();
}
Basically, I've got 2 enum classes inside following class.
firstfile.h
#include "secondfile.h"
class FirstFile
{
protected:
SecondFile secondobject;
public:
enum class enum1 {
Option1,
Option2
} enumIn = enum1::Option1;
enum class enum2 {
Option3,
Option4
} enumInOut = enum2::Option3;
// Methods
protected:
public:
void Function1();
};
firstfile.cpp
#include <iostream>
#include "firstfile.h"
void FirstFile::Function1()
{
std::cout << "Before the function call enumIn = Option 1 and enumInOut = Option3 " << std::endl;
secondobject.function2(enumIn, enumInOut);
if (enumInOut == enum2::Option4) {
std::cout << "After the function call enumInOut = Option 4" << std::endl;
}
else if (enumInOut == enum2::Option3) {
std::cout << "After the function call enumInOut = Option 3" << std::endl;
}
else {
std::cout << "enumInOut didn't match either Option 3 or Option 4" << std::endl;
}
}
The header file, where most of the errors occur.
secondfile.h
#include "firstfile.h"
class SecondFile
{
public:
void function2(const enum1& enumIn, enum2& enumInOut);
};
Finally, here is the method in class2 that is being called that should update enum2 based on the value of enum1.
secondfile.cpp
#include <iostream>
#include "firstfile.h"
#include "secondfile.h"
void SecondFile::function2(const enum1& enumIn, enum2& enumInOut)
{
if (enumIn == FirstFile::enum1::Option1) {
enumInOut = FirstFile::enum2::Option4;
}
}
The errors are:
firstfile.cpp
\secondfile.h(16, 28) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.h(16, 28) : error C2143 : syntax error : missing ',' before '&'
\firstfile.cpp(8, 42) : error C2660 : 'SecondFile::function2' : function does not take 2 arguments
\secondfile.h(16, 7) : message: see declaration of 'SecondFile::function2'
Main.cpp
\secondfile.h(16, 28) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.h(16, 28) : error C2143 : syntax error : missing ',' before '&'
secondfile.cpp
\secondfile.h(16, 28) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.h(16, 28) : error C2143 : syntax error : missing ',' before '&'
\secondfile.cpp(5, 39) : error C4430 : missing type specifier - int assumed.Note : C++ does not support default - int
\secondfile.cpp(5, 39) : error C2143 : syntax error : missing ',' before '&'
\secondfile.cpp(6, 6) : error C2065 : 'enumIn' : undeclared identifier
\secondfile.cpp(7, 3) : error C2065 : 'enumInOut' : undeclared identifier
Hope this all makes sense and look forward to any insights to help understand the cause of the errors and how I might be able to resolve them.
It's probably related to scope, but hoping to learn from this experience.
You have two issues:
You have circular dependencies, since you add the header of each classes to each other's header files. You can solve it via pointers members. Make the class member secondobject in the class FirstFile as a pointer, and provide a forward declaration in the header (i.e. in firstfile.h) for SecondFile.
Secondly, you need to specify the enum1 and enum2 from which class/ scope it is. You can use the using specifier for this, and enums will be available for the entire class SecondFile's scope.
That means, you need something like: (See Online)
firstfile.h
class SecondFile; // forward declaration
class FirstFile
{
protected:
SecondFile* secondobject{ nullptr }; // or smart pointers
public:
// ...enums and functions
};
firstfile.cpp
#include <iostream>
#include "secondfile.h"
void FirstFile::Function1()
{
// ...other code
if(secondobject)
secondobject->function2(enumIn, enumInOut);
// ^^^^^^^^^^^^
}
secondfile.h
#include "firstfile.h"
class SecondFile
{
public:
using enum1 = FirstFile::enum1; // specify from where the enums are
using enum2 = FirstFile::enum2;
void function2(const enum1& enumIn, enum2& enumInOut);
// ...other codes
};
secondfile.cpp
#include "secondfile.h"
void SecondFile::function2(const enum1& enumIn, enum2& enumInOut)
{
if (enumIn == enum1::Option1) {
enumInOut = enum2::Option4;
}
}

C++ Builder Pattern with Forward Declaration [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I recently got stuck in a situation. In the first version, everything is implemented in header file and it works fine. In the second version when i tried to separate implementation from header declarations, I got many errors. In the below lines, i m going to demonstrate problem. Thanks in advance..
First Version (it works fine!)
cameravalue.h
#ifndef CAMERAVALUE_H
#define CAMERAVALUE_H
#include <string>
class CameraValue
{
private:
class CameraProperties
{
private:
CameraProperties()
: mId(-1),
mName(),
mAddress(),
mExposure(),
mFocus()
{}
int mId;
std::string mName;
std::string mAddress;
std::string mExposure;
long long mFocus;
friend class CameraValue;
friend class CameraBuilder;
};
public:
class CameraBuilder
{
public:
CameraBuilder(int id)
{
mProperties.mId = id;
}
CameraBuilder& setName(std::string& name)
{
mProperties.mName = name;
return *this;
}
CameraBuilder& setAddress(std::string& adress)
{
mProperties.mAddress = adress;
return *this;
}
CameraBuilder& setExposure(std::string& exposure)
{
mProperties.mExposure = exposure;
return *this;
}
CameraBuilder& setFocus(int focus)
{
mProperties.mFocus = focus;
return *this;
}
CameraValue build()
{
return CameraValue(mProperties);
}
private:
CameraProperties mProperties;
};
private:
CameraValue(const CameraProperties& properties)
:mProperties(properties)
{}
CameraProperties mProperties;
};
#endif // CAMERAVALUE_H
main.cpp
#include "cameravalue.h"
#include <iostream>
int main(int argc, char *argv[])
{
CameraValue cm = CameraValue::CameraBuilder(1).setName(std::string("Huseyin")).build();
return 0;
}
Second Version (Don't work)
cameravalue.h
#ifndef CAMERAVALUE_H
#define CAMERAVALUE_H
#include <string>
class CameraValue
{
private:
class CameraProperties;
public:
class CameraBuilder;
private:
CameraValue(const CameraProperties& properties);
CameraProperties mProperties;
};
#endif // CAMERAVALUE_H
cameravalue.cpp
#include "cameravalue.h"
#include <string>
class CameraValue::CameraProperties
{
private:
CameraProperties()
: mId(-1),
mName(),
mAddress(),
mExposure(),
mFocus()
{}
int mId;
std::string mName;
std::string mAddress;
std::string mExposure;
long long mFocus;
friend class CameraValue;
friend class CameraBuilder;
};
class CameraValue::CameraBuilder
{
public:
CameraBuilder(int id)
{
mProperties.mId = id;
}
CameraBuilder& setName(std::string& name)
{
mProperties.mName = name;
return *this;
}
CameraBuilder& setAddress(std::string& adress)
{
mProperties.mAddress = adress;
return *this;
}
CameraBuilder& setExposure(std::string& exposure)
{
mProperties.mExposure = exposure;
return *this;
}
CameraBuilder& setFocus(int focus)
{
mProperties.mFocus = focus;
return *this;
}
CameraValue build()
{
return CameraValue(mProperties);
}
private:
CameraProperties mProperties;
};
CameraValue::CameraValue(const CameraProperties& properties)
: mProperties(properties)
{}
main.cpp
#include "cameravalue.h"
#include <iostream>
int main(int argc, char *argv[])
{
CameraValue cm = CameraValue::CameraBuilder(1).setName(std::string("Huseyin")).build();
return 0;
}
Compile Errors
cameravalue.cpp
c:\users\huseyin\documents\builderpattern\cameravalue.h(20) : error
C2079: 'CameraValue::mProperties' uses undefined class
'CameraValue::CameraProperties' ..\BuilderPattern\cameravalue.cpp(74)
: error C2440: 'initializing' : cannot convert from 'const
CameraValue::CameraProperties' to 'int'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
..\BuilderPattern\cameravalue.cpp(74) : error C2439:
'CameraValue::mProperties' : member could not be initialized
c:\users\huseyin\documents\builderpattern\cameravalue.h(20) : see declaration of 'CameraValue::mProperties'
c:\users\huseyin\documents\builderpattern\cameravalue.h(20) : error
C2079: 'CameraValue::mProperties' uses undefined class
'CameraValue::CameraProperties' ..\BuilderPattern\main.cpp(9) : error
C2440: '<function-style-cast>' : cannot convert from 'int' to
'CameraValue::CameraBuilder'
Source or target has incomplete type ..\BuilderPattern\main.cpp(9) : error C2228: left of '.setName' must
have class/struct/union ..\BuilderPattern\main.cpp(9) : error C2228:
left of '.build' must have class/struct/union
..\BuilderPattern\main.cpp(9) : error C2512: 'CameraValue' : no
appropriate default constructor available
..\BuilderPattern\main.cpp(10) : error C2039: 'getName' : is not a
member of 'CameraValue'
c:\users\huseyin\documents\builderpattern\cameravalue.h(8) : see declaration of 'CameraValue'
Definition of class CameraBuilder should be visible in main.cpp, so you can't just forward-declare it in cameravalue.h. But you can make the definitions of its member functions out-of-line:
// cameravalue.h
class CameraValue {
class CameraBuilder {
public:
CameraBuilder(int id);
...
};
};
// cameravalue.cpp
CameraValue::CameraBuilder::CameraBuilder(int id) {
...
}

C++ error C2143 syntax error : missing ';' before function name

I have header file :
#ifndef VIP_TICKET_H
#define VIP_TICKET_H
#include "ticket.h"
class VIPTicket : public Ticket
{
public:
enum VIPType { FIRST_CLASS, FAST_LINE };
VIPType getTicketType() const;
private:
VIPType type;
};
#endif
and it's cpp file
#include "vipTicket.h"
VIPType VIPTicket::getTicketType() const
{
return type;
}
the error says " error C2143: syntax error : missing ';' before 'VIPTicket::getTicketType' "
this error is very confusing.. i guess it's not a ';' that is missing but probably something else wrong with the code that I can't put my finger on..
The problem is this definition
VIPType VIPTicket::getTicketType() const
{
...
}
When you define this function you have to remember that VIPType is not in the global scope, but in the scope of the VIPTicket class, so you have to explicitly mention the scope:
VIPTicket::VIPType VIPTicket::getTicketType() const
{
...
}

C2039: Class is not a member of Namespace

Mage/Interface/Context.h
#pragma once
#include <Mage/Interface/Element.h>
#include <Mage/Renderer/RenderingContext.h>
#include <Mage/Renderer/VertexBuffer.h>
#include <glm/glm.hpp>
namespace Mage {
namespace Interface {
class Context {
protected:
RenderingContext* ctx;
VertexBuffer* vbo;
glm::mat4 projection;
Mage::Interface::Frame* uiParent;
public:
Context(RenderingContext* ctx);
~Context();
void render();
Mage::Interface::Frame* createFrame();
};
}
}
Mage/Interface/Element.h
#pragma once
#include <vector>
#include <Mage/Interface/Context.h>
#include <glm/glm.hpp>
namespace Mage {
namespace Interface {
class Element {
protected:
Mage::Interface::Context* ctx;
std::vector<Element*> children;
glm::vec3 position;
float scale;
public:
virtual void draw();
void attach(Element* child) {
this->children.push_back(child);
}
inline glm::vec3 getPosition() {
return this->position;
}
float getScale() {
return this->scale;
}
};
// Frame is an untextured, single colour quad. Frame may contain other
// Elements.
class Frame : public Element {
public:
Frame();
Frame(glm::vec3 pos);
Frame(float width, float height);
Frame(glm::vec3 pos, float width, float height);
};
}
}
This gives me the following errors:
Error C2039 'Context': is not a member of 'Mage::Interface' Mage2D c:\users\jesse\documents\visual studio 2015\projects\mage2d\include\mage\interface\element.h 14
Error C2238 unexpected token(s) preceding ';' Mage2D c:\users\jesse\documents\visual studio 2015\projects\mage2d\include\mage\interface\element.h 14
Error C2143 syntax error: missing ';' before '*' Mage2D c:\users\jesse\documents\visual studio 2015\projects\mage2d\include\mage\interface\element.h 14
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int Mage2D c:\users\jesse\documents\visual studio 2015\projects\mage2d\include\mage\interface\element.h 14
When I take out Mage::Interface::Context* ctx, the code compiles fine. I figured I must have missed a semi colon, but I can't see it - it all seems to check out just fine to me.
You have a circular dependency. Element.h includes Context.h and Context.h includes Element.h, that's not going to work.
The way to solve that is to forward-declare types instead of including their headers whenever you can, it'll also reduce compile times.

Syntax Error: Identifier 'string' error C2061

I'm having a hard time understanding why I get an error when I try to compile this.
Do I need to post my main too?
#ifndef SEARCHABLEADT_H
#define SEARCHABLEADT_H
#include <string>
template <typename T>
class SearchableADT
{
public:
virtual int loadFromFile(string filename) = 0;
//virtual void clear(void) = 0;
virtual void insertEntry(T value) = 0;
virtual void deleteEntry(T value) = 0;
virtual bool isThere(T value) = 0;
virtual int numEntries(void) = 0;
};
#endif
error is:
c:\users****\documents\visual studio 2012\projects\headersearchableadt\headersearchableadt\searchableadt.h(10): error C2061: syntax error : identifier 'string'
You could also use the next declaration:
#include <string>
using namespace std;
Although some one could argue that that's a bad coding habit.
Try: virtual int loadFromFile(std::string filename) = 0;.
Note the std::.