C++ :: Initializing Enum Member In Constructer
Jul 25, 2012
I am learning OOP Console Programming and i got some error in my code;
Here is my code
#include <iostream>
using namespace std;
enum ch {CD,DVD}
class disk {
private :
ch choice;
[Code] ....
I want to compare the enum variable to char c, and cout CD when user press 'c' and cout DVD when user press 'd'. I got error like this :
error : expected ')' before 'c' at first line after public
Note : I must use enum to store value.
View 7 Replies
ADVERTISEMENT
Jul 24, 2014
Here I'm trying to initialize PersonFactory::ethnicSurnames just once for the entire run of the program:
#include <iostream>
#include <string>
#include <vector>
#include <array>
enum Country {India, China, France, NumCountries}; // plus many other countries
struct School {}; struct Mall {}; struct HockeyArena {};
[Code] ....
Output:
PersonFactory::initializeEthnicNames() called
Carrying out the initialization...
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
PersonFactory::initializeEthnicNames() called
numberOfTimesInitialized = 1
As you can see, even though five PersonFactory objects were constructed, the ethnicNames initialization only occurred once, as desired. However, there are some issues with my method. First of all, the use of the comma operator is ugly in my opinion. But fashion statements aside, PersonFactory::initializeEthnicNames() is still called multiple times, which is not good, even though it correctly avoids reinitializing ethnicNames after the first call. Also, I now forever get the annoying compiler warnings that the bool namesInitialized is never used, which is true, thus wasting a small bit of memory. And finally, I cannot declare ethnicNames const now, and it is supposed to be const. Any better way to accomplish what I'm trying to do?
By the way, the reason why I don't initialize ethnic names outside the class as is normally done for static data members (and that would indeed allow me to declare it const) is because it would get messed up if I later change the order of the elements in enum Country. Hence actual lines of initializations I think are needed. And I do want ethnicSurnames inside PersonFactory, because I feel it really does belong there. Also, PersonFactory is not to be Singleton, because it has data members that depend on some parameters in its constructor (e.g. geographic location).
View 5 Replies
View Related
Apr 11, 2014
What I need to know is how I can pass an argument to the Book constructor so I can change the const data member Category (with cascading capacity if possible. I also posted some of my set functions for further comprehension.
class Book
{
friend void CompPrice(Book &,Book&); //friend function that has access to the member functions of this class
//The arguments sent to it are by address, and of type the class Book, so that it can have access to its member functions
private: //private data members
[Code].....
View 2 Replies
View Related
Jan 23, 2015
I have a class that defines a window (a popup dialog of sorts), and I want the name of that window to be constant. The only problem is that the name of the popup needs to match the title of the parent window, and I get the name of the parent in the constructor. So how do I go about defining this member variable to be constant and initializing it with a value in the constructor?
I want to do something like this, but I know this isn't allowed:
/* class.h */
class foo {
public:
foo(*parentWindowPtr);
[Code] .....
I should mention that yes the name of the parent window is const char *, and I would like to keep it this way.
View 4 Replies
View Related
May 29, 2013
I really confused with constructor (default constructor and constructor with parameters)
I coded this problem
and I worked almost, but I stock in constructor
Code:
class Tier {
public:
enum TIER_MAKE
[Code] ....
This is tier class and I have to finish constructor in class car (for simple, I skip detail code) -red things are the parts from class Tier
Code: Car()
: make(NULL), passengers(0), fuelcap(0.0), efficiency(0.0), tier(Tier::nexen)
{ }
[Code] ....
And someone said default constructor part has to be this
Code:
car( Tier::TIER_MAKE p_tiermaker = Tier::nexen )
//after i skip
but default constructor should be no parameter...? isn't it?
View 1 Replies
View Related
Jan 19, 2014
I'm trying to make a simple C++ program in which the user must try to guess a number, if they guess too high it says "too high" and if they guess too low it says "too low".
I also decided to add a feature which allows them to select how many tries they would like to guess the number. I tried to make "tries" type an enum so if the user could not pick an invalid number but for some reason i cannot use it in an if statement.
here is the code and i am getting the first error on line 27:
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int guess;
[Code]....
View 7 Replies
View Related
Apr 1, 2013
I am trying to write a game in C++ with SDL, and I have a class that allows me to handle events. The class is actually really simple: It takes the SDL_Event, then 2 variables from 2 different enum to determine for which Event and which Key should be checked, and then a variable that will be modified if the event happens. Here is the class
EventParser.h
#include "SDL.h"
#include "SDL_opengl.h"
template<class T>
[Code]...
As of yet the variable only changes if the Left key has been released, it will be extended if the error has been solved.
Then, in my main.cpp file I define the Event and the EventParser as
SDL_Event event;
EventParser<float> ep;
And in a loop, the parseEvent function is called like this:
ep.parseEvent(event, ep.KeyUp, ep.LEFT, &xVariable);
However I get a linker error (not the first one I got when programming this game)
error LNK2019: unresolved external symbol "public: void __thiscall EventParser<float>::parseEvent(union SDL_Event,enum EventParser<float>::EventType,enum EventParser<float>::KbdKey,float *)" (?parseEvent@?$EventParser@M@@QAEXTSDL_Event@@W4EventType@1@W4KbdKey@1@PAM@Z) referenced in function _SDL_mainC:UsersPrideRageDocumentsVisual Studio 2012ProjectsSDL_TestSDL_Testmain.objSDL_Template
View 6 Replies
View Related
Sep 30, 2014
I have an enum like:
Code:
typedef enum mac_type_e{
STATIC_MAC,
BLACKLIST_MAC
} mac_type_t; and I want to use this type in a structure that's declared like:
Code:
typedef struct lan_mac_s {
UINT16 lanmacid;
enum mac_type_t lan_mac_type_pp;// user mac type per port, 20 mac_type_t array, 0 = static, 1 = blacklisted now,
The compiler tells me:
Code:
incomplete type is not allowed
enum mac_type_t lan_mac_type_pp;// user mac type per port, 20 mac_type_t array, 0 = static, 1 = blacklisted
But if I remove the preceeding "enum" keyword, it compiles fine.
View 2 Replies
View Related
Feb 3, 2014
I defined
enum symbol {A, B, C};
in file A.h
and in file B.h, I #include "A.h" , but still get error of A , B and C unresolved when using them. WHy?
View 15 Replies
View Related
Jul 4, 2014
I'm trying to convert the enum type {PG, R, G, PG-13, etc.} to strings so i can use it in cout statement but no matter what i put inside switch(), the compiler keeps saying Error: expression must have integral or enum type. What am I doing wrong exactly?
Movie covert_rating(Movie r) {
switch (r) {
case PG:
return "PG";
break;
case R:
return "R";
[code]....
View 4 Replies
View Related
Jan 25, 2015
I want to convert an enum to a text string.
enum BREED {YORKIE,CAIRN,DANDIE,SHETLAND,DOBERMAN,LAB};
View 4 Replies
View Related
Apr 2, 2012
Any way to use a string to access a specific item in a matrix of int[X].
I have a program which uses enums as iterators to reference a large amount of data. To select an item in the matrix, the user will enter a string, which is also an enum, which also must serve as an iterator for something in the matrix. Here is a toybox example:
#include <iostream>
#include <string>
using namespace std;
enum NyNumbers { First, Second, Third, Forth, LAST_VALUE };
int main(int argc, char* argv[]) {
int Matrix[LAST_VALUE] = { 1, 3, 7, 12 };
[Code] .....
The idea is the user executes the program by typing "./RUN First" to print out the first element in the MyNumbers array, "./RUN Second" to access the second, and so on. I can't use static numbers for the iterator. (i.e., "./RUN 1") I must reference by enum/string.
When run, the output of this problem is thus:
====================================================================
user@debian$ ./RUN Second
Matrix[ atoi(Second) ]: 1
user@debian$
====================================================================
BTW, if I change line 12 to this
====================================================================
cout<<Matrix[ argv[1] ]<<"
";
====================================================================
The error message is this
====================================================================
user@debian$ make
g++ -g -Wall -ansi -pg -D_DEBUG_ Main.cpp -o exe
Main.cpp: In function `int main(int, char**)':
Main.cpp:12: error: invalid types `int[4][char*]' for array subscript
make: *** [exe] Error 1
user@debian$
====================================================================
Which isn't unexpected. How to input the enum as argv[1]?
View 2 Replies
View Related
Aug 31, 2013
As we know in C there is no checking if values passed to a function that takes enum are correct, that is if they have been defined in this enum. Example from Enums in C | Occasionally sane ([code] tags don't work on my fx 18.0.1 this is why I put in on pb): [URL] ......
Here c - How to check if an enum variable is valid? - Stack Overflow they say that common convention is add check whether value passed as the parameter is not bigger than the maximum value in enum. But how about situations when enum is composed of numbers from 1-20 and then from 500-510?
View 4 Replies
View Related
Dec 2, 2013
I defined
enum boundaryType_t {inside, inlet, outlet, wall, periodic};
now I have file written like this:
inside outlet
I want my program read the file and when encounter any enum type, instead of treating it as a string, I want the program store it in memory as a enum value.
How can I do that?
string s;
ifs>>s;
s // how to convert it to enum???
View 5 Replies
View Related
Feb 25, 2014
It is working:
#include <iostream>
#include <string>
#include <vector>
#include <map>
const int ENUM_NOT_FOUND = -1; const std::string NEW = " ";
enum Day {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
[code]....
Ouput with GCC 4.8.1:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Name a day: Friday
day = Friday
But the problem is that whenever I define a new enum, I have to define the << and >> overloads for the new enum again. Isn't there a way to template that as well, so that the << and >> overload needs to be defined just once? My atttempt:
template<typename Enum>
std::ostream& operator << (std::ostream& os, Enum en) {
return os << EnumConversions<Enum>::toString (en);
[Code] .....
fails to compile. I guess the problem is Enum is not known at compile time, even though it should be deducible during run time? Error mentions ambiguous overload for operator>>.
View 6 Replies
View Related
Oct 13, 2014
I need to do this simple Battleship game project for my C++ class. Here is my current code so far:
#include <iostream>
#include <array>
#include <string>
using namespace std;
enum BShip{ EMPTY, BTLSHIP, HIT, MISS };
const int BSIZE = 6;
const int BTLSHIP_SIZE = 4;
class Battleship {
private:
array<array<Bship, BSIZE>, BSIZE> sea, hits;
[code]....
For some reason, I'm getting errors on the string and enum declarations.
View 10 Replies
View Related
May 7, 2013
Is there a quick way to determine if a value is in an enum? Consider for example,
public enum GenderEnum
{
Unknown = 0,
[Code].....
I don't want to convert to an array if possible, just check the enum and get a yes/no answer.
View 1 Replies
View Related
Sep 6, 2014
So far I have the following code:
// Purpose: To write a program that displays the number of millimeters higher the current level the ocean level will be in
// in 5, 7, and 10 years.
# include <iostream>
# include <string>
using namespace std;
int main() {
float X = 10;
string Y="";
[Code] ....
But I get the following error message:
IntelliSense: expession must have integral or unscoped enum type
three times in a row for lines 25, 27, and 29 and I don't understand or know why?
In case the purpose does make sense here are the directions:
2.7: Ocean Levels
Assuming the ocean’s level is currently rising at about 1.5 millimeters per year, write a program that displays
•The number of millimeters higher than the current level that the ocean’s level will be in 5 years,
•The number of millimeters higher than the current level that the ocean’s level will be in 7 years,
•The number of millimeters higher than the current level that the ocean’s level will be in 10 years,
Output labels:
Each value should be on a line by itself, preceded by the a label of the form:
In X years the ocean's level will be higher by Y millimeters.
where X is the number of years (5, 7 or 10) and Y is the value you calculate.
View 16 Replies
View Related
Feb 23, 2014
I get the following error in XCode whenever I try to access the member I created 'randomGen' in a separate class in a different header file. I have made sure to include the header file and have tried to access it through an object.
This is the code I enter when trying to access the method from randomiser.h in main.cpp. It is also an overloaded function with doubles and integers:
RandomG randomiser;
randomiser.randomGen(); // 'Call to member function 'randomGen' is ambiguous'
This is the code inside randomiser.h:
#include <string>
#include <iostream>
using std::string;
using std::cout;
using std::endl;
class RandomG {
[Code] ....
This is the error inside xcode: [URL] ....
I have tried seperating the code for the functions in another class (main.cpp) and then running and it seems to works, so I'm not sure why I can't put everything in the .h file and then access it?
I would like it in a seperate file so it doesn't clutter my main. I am writing a game with SDL so that might be confusing and I would like the window to have a random title and other random properties, so it would be easier to use a function.
View 3 Replies
View Related
May 21, 2014
I have been working a project in C++. I have TTTMain.cpp file that has all the function calls, TTTFuntions.cpp that has all the functions, I have TTT.h file that has all the prototypes and variables and additionally I have Winner.h that has enum class Winner declaration in it. Here is my block of codes:
Winner.h file:
#ifndef winner
#define winner
enum class Winner {
[Code]....
My question is when I compile this gives me error on
Winner gameSquares[] = { Empty, Empty,Empty, Empty, Empty, Empty, Empty, Empty, Empty };
with saying "invalid use of non-static data data member" and It says "Empty was not declared in this scope."
I know calling enum is very very trick.
View 3 Replies
View Related
Mar 6, 2015
I am making a tictactoe program that requires me to have a 3 by 3 two dimensional array of integers, in which the constructor should initialize the empty board to all zeroes. The program complies, but it keeps outputting garbage values and i'm not entirely sure why, My print function isn't complete yet, since I want to print out the array in a tic tac toe format, but i'm more concerned with why it's printing garbage values, here is my code:
Code:
// header file
#include <iostream>
#include <array>
[Code] ....
View 7 Replies
View Related
Sep 26, 2014
I am working on a homework assignment and have most of the program working, but when I try to compile it keeps telling me to initialize the coin variables in each class. However, they are supposed to be added then removed so I don't want to set them back to zero.
Rewrite the Purse program given in Page 35 with functions to perform insert and remove operations. The function insert (int p, int n, int d, int q) will initialize pennies, nickels, dimes and quarters. The function dollars() will return the dollars. The function remove (int p, int n, int d, int q) will subtract pennies, nickels, dimes and quarters. The function display() returns a new String to print the content of the purse with remaining pennies, nickels, dimes and quarters.
Code:
usingnamespace std;
int insert_money (int *p, int *n, int *d, int *q);
int remove_money (int *p, int *n, int *d, int *q);
int dollars();
int main()
[Code] ....
View 2 Replies
View Related
Oct 7, 2014
I am having issues with trying to implement JameM's kernel. I page fault attempting to assign the return value of place_ordered_array into the kheap.The malloc function should remain between 10000000-20000000 yet I exceed this. I have a hunch it's due that I am using grub2 (he uses legacy) and it loads modules at a higher address. I tested this by debugging at alloc and found that the function cannot handle above about 20000000. Am I on track to say I must attempt to move the module or code to prevent trampling or that I should switch to legacy.
View 1 Replies
View Related
Oct 24, 2013
I want to know how to make variables during the program. for example in a program i want to have the player be able to create their own spells or add their own weapons to the game without having to edit the source code. i use sfml 2.0
View 4 Replies
View Related
Feb 4, 2014
I came across a piece of c++ code that seems to be initializing a class object like this:
ImapMailbox *mailbox;
Now the class looks like this:
class ImapMailbox {
public:
ImapMailbox();
ImapMailbox (const QString& mailbox);
~ImapMailbox();
// Methods
void addMessage (ImapMessage *message);
[Code]...
And the constructor looks like this:
ImapMailbox::ImapMailbox()
: d(new ImapMailboxPrivate)
{
d->unseen = d->exists = d->recent = 0;
d->readWrite = false;
d->flags = 0;
}
But this does not seem to be an array like object. So what exactly could this be pointing to?
View 2 Replies
View Related
Oct 15, 2013
sth is in my mind.
fast way of initializing an object through constructor is
Fred::Fred() : x_(whatever) { }
slow way
Fred::Fred() { x_ = whatever; }
ok. i accept it is faster but why?? what is the difference compiler does.
View 6 Replies
View Related