Passing enum as parameter to a constructor [closed] - c++

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 7 years ago.
Improve this question
I got a problem when I want to pass an enum value to a default construtor. My enums are defined like this:
typedef enum
{
DOUBLOON,
VICTORYPOINT
} ENUMchipType;
They are stored in a separate .h file.
But when i try to do this:
chips m_doubloon(DOUBLOON);
I get the following error:
error: C2061: syntax error : identifier 'DOUBLOON'
The code for the default constructor is:
chips::chips(
ENUMchipType chipType = DOUBLOON,
int amountValue1 = 0,
int amountValue5 = 0,
QObject *parent = 0) :
m_chipType(chipType),
m_chipCountValue1(amountValue1),
m_chipCountValue5(amountValue5),
QObject(parent) {}
Anyone an idea what is wrong with this piece of code? Thanks in advance!
Edit: I already tried putting the enum is a class als a public member and derive the chips class from it, but without any succes.
EDIT 2: This piece of code reproduces the error in Visual Studio 2013
#include <string>
using namespace std;
//enums.h
typedef enum
{
DOUBLOON,
VICTORYPOINT
} ENUMchipType;
typedef enum
{
PLAYER1,
PLAYER2,
PLAYER3,
PLAYER4,
PLAYER5
} ENUMplayer;
// In chips.h
class chips
{
private:
int m_chipCountValue5;
int m_chipCountValue1;
ENUMchipType m_chipType;
public:
explicit chips(
ENUMchipType chipType = ENUMchipType::DOUBLOON,
int amountValue1 = 0,
int amountValue5 = 0);
ENUMchipType getChipType() const { return m_chipType; }
};
// Chips.cpp
chips::chips(ENUMchipType chipType, int amountValue1, int amountValue5) :
m_chipType(chipType),
m_chipCountValue1(amountValue1),
m_chipCountValue5(amountValue5) {}
// PLayer.h
class player
{
private:
ENUMplayer m_ID;
string m_name;
public:
chips m_doubloon(DOUBLOON);
chips m_victoryPoints(VICTORYPOINT);
explicit player(ENUMplayer ID = PLAYER1, string name = "");
void setName(string name = "") { m_name = name; }
void setID(ENUMplayer ID) { m_ID = ID; }
string getName() const { return m_name; }
ENUMplayer getID() const { return m_ID; }
};
//player.cpp
player::player(ENUMplayer ID, string name) :
m_ID(ID),
m_name(name) {}
int main() {
return 0;
}

Now you've finally posted enough code, we see that this
chips m_doubloon(DOUBLOON);
is actually a class member declaration. Class members can't be initialised with (), only with = or {}. Assuming your compiler supports in-class initialisation (introduced in C++11), you should be fine with
chips m_doubloon{DOUBLOON};
^ ^
Alternatively, you could initialise the members in the constructor's initialiser list rather than in their declarations.

In class player, you should replace
chips m_doubloon(DOUBLOON);
chips m_victoryPoints(VICTORYPOINT);
by
chips m_doubloon{DOUBLOON};
chips m_victoryPoints{VICTORYPOINT};

You need to pass DOUBLOON as ENUMchipType::DOUBLOON

Related

Why is my class constructor being called twice?

I've got a base class Container with a derived class Player_Inventory. There can only be one Player_Inventory so my code throws an exception if for some reason a second one is created.
The problem I'm having is that my code is failing my test as it throws the exception even on what is supposed to be the very first construction of the Player_Inventory class. I've debugged the code and two things are happening which I don't quite understand - the number attribute is not tracked by the debugger (at least not in the GUI on VSC), and it seems that right after hitting the first REQUIRE statement, the constructor is called again, thus triggering the exception.
Can anyone help?
After rewriting my constructor method, I'm still getting a similar error.
My revised code is as follows:
containers.h
#include<iostream>
#include<string>
#include<vector>
class Item { // Placeholder class for items
public:
std::string name;
Item(std::string n) : name{n} {};
};
class Container {
protected:
std::string name;
std::string description;
std::vector<Item> contents;
public:
Container(std::string, std::string);
std::string get_name() {return name;}
std::string get_description() {return description;}
std::vector<Item> get_contents() {return contents;}
};
containers.cpp (there are more methods defined in this file which aren't used here)
#include<iostream>
#include<string>
#include "containers.h"
Container::Container(std::string n, std::string desc) : name{n}, description{desc} {};
player_inventory.h
#include "containers.h"
class Player_Inventory : public Container {
public:
static int number;
Player_Inventory(std::string, std::string);
};
player_inventory.cpp
#include<iostream>
#include<stdexcept>
#include "player_inventory.h"
Player_Inventory::Player_Inventory(std::string n, std::string desc): Container(n, desc) {
number += 1;
if (number > 1){
throw std::invalid_argument("You can only have one inventory!");
}
};
int Player_Inventory::number = 0;
test_file.cpp
#include "../lib/Catch2/catch.hpp"
#include "player_inventory.h"
#include<iostream>
#include<string>
#include<vector>
SCENARIO("A player can have an inventory.") {
WHEN("A player inventory is created.") {
Player_Inventory myInventory("My Inventory", "Inventory for the player");
THEN("The created inventory has the correct attribute values.") {
REQUIRE(myInventory.get_name() == "My Inventory");
REQUIRE(myInventory.get_description() == "Inventory for the player");
REQUIRE(myInventory.get_contents().empty());
} // The code works fine when only up to here is included
AND_THEN("Only one player inventory can exist.") { // as soon as this line is included it tries to create another player_inventory object, causing the fail
REQUIRE_THROWS((Player_Inventory myOtherInventory("Second Inventory", "Testing for another one"))); // These two lines were not included but I've included them here as this is the test I wanted to run
REQUIRE(myInventory.get_number() == 1);
}
}
}
Not sure if related, but that's how you should call the Base constructor:
Player_Inventory(std::string n, std::string desc) : Container(n, desc) {
}

How can one update a class member/value from a function in c++ [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have a class representing a player. Separated into a header and a source like this.
#include "player.h"
player :: player(std::string name,int money,int position,int pcode)
: name(name), money(money), position(position), pcode(pcode)
{}
void player::setPlayer(std::string name,int money,int position,int pcode){
name=name;
money=money;
position=position;
pcode=pcode;
}
void player::setName(std::string name){
name = name;
}
void player::setMoney(int money){
money = money;
}
void player::setPosition(int position){
position = position;
}
void player::setcode(int pcode){
pcode = pcode;
}
header
#ifndef PLAYER_H_INCLUDED
#define PLAYER_H_INCLUDED
#include <string>
class player
{
private:
std::string name;
int money;
int position;
int pcode;
public:
player(std::string name,int money=0,int position=0,int pcode=0);
virtual void setPlayer(std::string name,int money,int position,int pcode);
virtual void setName(std::string name);
virtual void setMoney(int money);
virtual void setPosition(int position);
virtual void setcode(int code);
std::string getName() { return name; }
int getMoney() { return money; }
int getCode() { return pcode; }
int getPosition() { return position; }
//players code
};
#endif // PLAYER_H_INCLUDED
I want to update the value of an instance of the player but it is not retaining the value, every iteration falls back to the initial declaration.
I have tried passing reference but it still doesn't work.
void func_pos(CSquare squares[],player* me, player* opponent)
{
int g;
g = Random();//random generator func
me->setPosition(10);
std::cout<<me->getPosition()+g<<std::endl;
}
Function use
player car("Player 2", 1500, 0, 2);
player car("Player 2", 1500, 0, 2);
func_pos(squares, &dog, &car);
any assistance is appreciated
Giving a class member function's parameters the same name(s) as class data members is, IMHO, poor practice (although I see it a lot, here on Stack Overflow).
Consider your setName function:
void player::setName(std::string name){
name = name;
}
The code in this function doesn't change anything in the class instance on which it is called. Rather, it assigns the value of the given name string parameter to ... the given name string parameter. Thus, it achieves nothing.
If you insist on using such confusing parameter names, then you can disambiguate inside the function using the this-> class pointer:
void player::setName(std::string name){
this->name = name;
}
However, I think it is far better to use different names for your parameters:
void player::setName(std::string name_argument){
name = name_argument;
}
You have (of course) similar issues in a number of your other class functions.
With compiler warnings fully enabled, you would readily spot these issues. For the setName function in your code, the MSVC compiler gives:
warning C4458: declaration of 'name' hides class member
and clang-cl shows:
warning : declaration shadows a field of 'player' [-Wshadow]
warning : explicitly assigning value of variable of type 'std::string'
(aka 'basic_string<char, char_traits, allocator >') to
itself [-Wself-assign-overloaded]

Error LNK2001 in Visual Studio 2017 when using static int [duplicate]

This question already has answers here:
How to initialize private static members in C++?
(18 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 3 years ago.
I'm doing some practice tasks for uni and I'm supposed to create static int field inside a class, but when I do so I get error LNK2001. When I change it to regular int the error does not occure. Can anybody help me please? Here's my code:
#include <iostream>
#include <string>
using namespace std;
class Uczelnia {
public:
virtual string getName() = 0;
static int liczba_wszystkich_studentow;
};
class Politechnika:public Uczelnia {
public:
Politechnika(string a, int b) {
nazwa = a;
liczba_studentow = b;
liczba_wszystkich_studentow = +liczba_studentow;
}
string getName() {
cout << "Politechnika: " << nazwa << endl;
return nazwa;
}
~Politechnika() {
liczba_wszystkich_studentow = -liczba_studentow;
}
private:
string nazwa;
int liczba_studentow;
};
class Uniwersytet :public Uczelnia {
public:
Uniwersytet(string a, int b) {
nazwa = a;
liczba_studentow = b;
liczba_wszystkich_studentow = +liczba_studentow;
}
string getName() {
cout << "Uniwersytet: " << nazwa << endl;
return nazwa;
}
~Uniwersytet() {
liczba_wszystkich_studentow = -liczba_studentow;
}
private:
string nazwa;
int liczba_studentow;
};
int main() {
Politechnika p1("Warszawska", 200);
p1.getName();
Uniwersytet u1("Warszawski", 600);
}
You're getting a linker error because you haven't initialized the static member.
You just need to initialize it outside of the class.
class Uczelnia {
public:
//..
static int liczba_wszystkich_studentow;
//..
};
int Uczelnia::liczba_wszystkich_studentow = 5;
There are some additional intricacies of being able to initialize static const integral types (like int) inside of the class, but with others you would typically initialize these static members in the source file outside of the class definition.
Within a class definition there are declarations of static data members not their definitions. Declared static data members within a class definition may even have an incomplete type. If a static data member is ODR used it shall be defined outside a class definition in some module. For example
int Uczelnia::liczba_wszystkich_studentow;
In C++ 17 you can use the inline specifier in a declaration of a static data member within a class definition.
For example
class Uczelnia {
public:
virtual string getName() = 0;
inline static int liczba_wszystkich_studentow;
};
In this case the code will compile provided that the compiler supports C++ 17..

error C2509: member function not declared in derived class [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 have base class State and derived class InitialState.When i build solution compiler show error C2509: 'setView': member function not declared in 'InitialState' and I don't know why...
Here is State.h :
#ifndef STATE_H
#define STATE_H
#include<iostream>
using namespace std;
class State {
public:
State() { isPrototype = true; }
virtual void execute() = 0;
virtual void setView(ostream& screen) const = 0;
virtual void onEnter() { system("CLS"); setView(cout); }
virtual void onExit() = 0;
private:
bool isPrototype;
State* nextState;
};
#endif
InitialState.h :
#ifndef INITIAL_STATE_H
#define INITIAL_STATE_H
#include"State.h"
class InitialState : public State {
public:
void execute() {}
void onExit() {}
void setView(ostream& screen) const;
};
#endif
and InitialState.cpp:
#include"InitialState.h"
void InitialState::setView(ostream& screen) const {
screen << "Welcome!" << endl;
screen << "Please select what you want to do: " << endl << "1.Load card" << endl << "0.Exit" << endl;
}
I have tried to add key word "virtual" in the front of functions in InitialState.h , but it doesn't change anything...also when I delete InitialState.cpp the code compiles normaly.
Here is the AtmTest.cpp:
#include "PaymentCard.h"
//#include "Atm.h"
int main() {
return 0;
}
but it has nothing with State...
and here are the other classes:
Atm.h:
#ifndef ATM_H
#define ATM_H
#include<iostream>
using namespace std;
class Atm {
public:
static Atm* get();
static void release() { delete instance; instance = nullptr; } //Singleton
private:
int serialNumber;
string bankName;
string location;
//Singleton:
Atm();
static Atm* instance;
Atm(const Atm& m) = delete;
Atm& operator=(const Atm& m) = delete;
Atm(Atm&&) = delete;
Atm& operator=(Atm&& m) = delete;
};
#endif
Atm.cpp:
#include"Atm.h"
//Singleton:
Atm* Atm::instance = nullptr;
Atm* Atm::get() {
if (instance == nullptr) {
instance = new Atm();
}
return instance;
}
PaymentCard.h:
#ifndef PAYMENT_CARD_H
#define PAYMENT_CARD_H
#include<iostream>
using namespace std;
class PaymentCard {
public:
PaymentCard(string clientName);
void addMoney(unsigned int amount) { currentAmount += amount; }
void withdrawMoney(int amount);
friend ostream& operator<< (ostream&, const PaymentCard&);
private:
static int NumberGenerator;
unsigned int serialNumber;
string clientName;
int currentAmount;
};
#endif
PaymentCard.cpp:
#include"PaymentCard.h"
int PaymentCard::NumberGenerator = 0;
PaymentCard::PaymentCard(string clientName) {
currentAmount = 0;
this->clientName = clientName;
serialNumber = NumberGenerator++;
}
void PaymentCard::withdrawMoney(int amount) {
if (amount > currentAmount)cout << "Ovde ide izuzetak";
else currentAmount -= amount;
}
ostream& operator<< (ostream &os, const PaymentCard& card){
os << card.serialNumber + 1 << ". Client: " << card.clientName << endl;
return os;
}
This code is not near the finish, but it worked until i have made SetView in InitialState, so idk what happened..
The problem: InitialState.h is precompiled, and you are linking to a prior version of InitialState.h. Clean, rebuild, and/or disable precompiled headers altogether.
I suspect that, because:
I can reproduce the error by commenting out the declaration of setView() in InitialState.h
The resulting error message refers to line 3 of InitialState.cpp and the error message you posted refers to line 6, which indicates that the posted source code did not produce that error message.
To reproduce the error, one has to comment out the setView() decalration from the InitialState class:
class InitialState : public State {
public:
void execute() {}
void onExit() {}
//void setView(ostream& screen) const;
};
Then one gets the following error message:
1>InitialState.cpp(3): error C2509: 'setView' : member function not declared in 'InitialState'
1> c:\users\laci\desktop\samples\stackoverflow\InitialState.h(6) : see declaration of 'InitialState'

What is wrong? - Composition compile error (with family+person classes example)

I got two classes, one named Person that I checked is working (I can create objects of that class so the problem should not be here).
I then have another class called Family with composition from Person:
Family.h
#include "Person.h"
class Family
{
public:
Family();
void printFamily();
private:
Person dad_();
Person mum_();
Person son_();
Person daughter_();
};
Family.cpp
#include "Family.h"
Family::Family()
{
}
void printFamily()
{
dad_.printAll();
mum_.printAll();
son_.printAll();
daughter_.printAll();
//printAll() is a function in the Person class that worked when
//I tested it earlier with only the person class
}
But when i try to compile this I get an error:
left of '.printAll' must have class/struct/union
'son_' : undeclared identifier
This error goes for all the .printAll() calls in family.cpp.
I can't see why this wouldn't work, so I hope you can.
Edit1:
Ok i changed
void printFamily()
to
void Family::printFamily()
That removes one error, but i still get
left of '.printAll' must have class/struct/union
Edit2
Ah my bad with the Person calls i changed them to
Person dad_;
and the same with the rest.
Seems like their might be an error with my Person class so i will post that also
Person.h
#include <string>
using namespace std;
class Person
{
public:
Person( const string & = "000000-0000", const string & = "N", const string & = "",const string & = "N");
~Person();
void setFirstName(const string &);
void setMiddleName(const string &);
void setLastName(const string &);
void getData(string &,string &,string &,string &);
static int getNumberOfPersons();
void printPartially() const;
void printAll() const;
bool checkForSameName(const Person &);
private:
string firstName_;
string middleName_;
string lastName_;
string socialSecNumber_;
static int numberOfPersons_;
};
Person.cpp
#include "Person.h"
#include <iostream>
int Person::numberOfPersons_ = 0;
Person::Person( const string &sNumber, const string &firstName, const string &middleName,const string &lastName )
:firstName_(firstName),middleName_(middleName),lastName_(lastName),socialSecNumber_(sNumber)
{
numberOfPersons_ ++;
}
Person::~Person()
{
numberOfPersons_--;
}
void Person::setFirstName(const string &firstName)
{ firstName_ = firstName; }
void Person::setMiddleName(const string &middleName)
{ middleName_ = middleName; }
void Person::setLastName(const string &lastName)
{lastName_ = lastName;}
void Person::getData(string &fName,string &mName,string &lName,string &sNumber)
{
fName = firstName_;
mName = middleName_;
lName = lastName_;
sNumber = socialSecNumber_;
}
int Person::getNumberOfPersons()
{
return numberOfPersons_;
}
void Person::printPartially() const
{
cout <<"Navn: "<<firstName_<<" "<<middleName_<<" "<<lastName_<<endl;
cout <<"Født: ";
for (int i = 0;i<6;i++)
{
cout <<socialSecNumber_.at(i);
}
}
void Person::printAll() const
{
cout <<"Navn: "<<firstName_<<" "<<middleName_<<" "<<lastName_<<endl;
cout <<"Personnr: "<<socialSecNumber_<<endl;
}
bool Person::checkForSameName(const Person &p)
{
if (p.firstName_ == firstName_ && p.middleName_ ==middleName_ && p.lastName_ == lastName_)
return true;
else
return false;
}
Now i am getting some new errors:
error C2011: 'Person' : 'class' type redefinition
see declaration of 'Person'
'Family::dad_' uses undefined class 'Person'
The "dad" error applies to the whole family
You have a few syntax issues.
First, you're declaring each of what are supposed to be member variables as functions which return Person. They should look like (note, no parens):
Person dad_;
Person mum_;
Person son_;
Person daughter_;
You're also missing the scoping on your definition of printFamily:
void Family::printFamily() {
...
}
Without the preceding Family::, C++ thinks you're defining a free function, and doesn't know to look inside the Family class for the declarations of dad_, mum_, etc.
Additionally, at least with the code you've shown, there's no way to initialize the people in your class. The Family constructor should take arguments to define the people, or you should have setters which allow defining them later. Right now, you'll get 4 identical people, set up however the default person constructor builds them.
I would normally prefer the constructor method, but I have other design reservations about your code to begin with (e.g. Does a family always contain mum, dad, brother, sister?) and that's not really what this question is about.
The line:
Person dad_();
says that dad_ is a function that returns a Person, not an object. Did you mean that? Similarly for others.
Try
Person dad_;
Family.h
#include "Person.h"
class Family
{
public:
Family();
void printFamily();
private:
Person dad_;
Person mum_;
Person son_;
Person daughter_;
};
Family.cpp
#include "Family.h"
Family::Family()
{
}
void Family::printFamily()
{
dad_.printAll();
mum_.printAll();
son_.printAll();
daughter_.printAll();
//printAll() is a function in the Person class that worked when
//I tested it earlier with only the person class
}
The out of line definition of a member function needs to include the class name:
void Family::printFamily()
{
//...
Surprisingly, you already got this right for the constructor but then immediately forgot...
Second, your private class members are functions, not data members (which is odd), but if that's deliberate, you need to call them:
dad_().printAll();
// ^^^