What is the problem with the following code is? It compiles with Visual C++ 2012 but does not with g++:
//a.h
#ifndef Loaded
#define Loaded
using namespace std;
class MyClass{
public:
static const int MyStaticValue = 200;
[Code] ....
If I try to compile this using the command
g++ a.cpp b.cpp
I get an "undefined reference to 'MyClass::MyStaticValue'" error for the line "A = MyClass::MyStaticValue;" in main(). The strange thing is that if I change the line to "A = (int) MyClass::MyStaticValue;" it works fine and the output is
200
200
as expected.
The code also compiles under g++ if I move the defintion of MyStaticValue from a.h to a.cpp by const int MyClass::MyStaticValue = 200;
I am having a problem concerning a static const member variable I want to use to set a certain property of my class during development time. The question actually concerns proper implementation as I do have a solution that "works" at least. The variable should denote the size of a member array which I don't want to allocate on the heap due to serious performance issues. So here is my code:
//MyClass.h class MyClass{ public: static const int MyArraySize = 256; private: int MyArray[MyArraySize]; };
This works but it's not nice for two reasons:
1) It doesn't separate interface from implementation. I would prefer to define the variable in the corresponding .cpp file but it doesn't work:
//MyClass.h class MyClass{ public: static const int MyArraySize;
[Code] .....
If I delete the line int MyArray[MyArraySize]; the above code works but when I use it to define the size of the array I get a "constant expression expected" error for the line int MyArray[MyArraySize]; which makes sense as the compiler does not know the value of MyArraySize when he reaches int MyArray[MyArraySize]; and therefore can not allocate the memory. Of course I can move MyArray to the heap like that:
//MyClass.h class MyClass{ public: static const int MyArraySize; static const int MyValue;
[Code] .....
But as I mentioned before this causes a remarkable loss of performance.
Something like the following does not work:
//MyClass.h class MyClass{ public: static const int MyArraySize = (int) pow(2, 8); private: int MyArray[MyArraySize]; };
This gives a "constant expression expected" error for the line static const int MyArraySize = (int) pow(2, 8);
Interestingly the following code works:
//MyClass.h class MyClass{ public: static const int MyValue; };
//MyClass.cpp #include "MyClass.h" const int MyClass::MyValue = (int) pow(2, 8);
So if I use pow outside of the class definition I get no errors. Is there any solution to those problems? So what I want is: 1) Don't allocate the array on the heap 2) Separate interface from implementation 3) Being able to use functions like pow to define MyArraySize 4) Not use global variables
I need to keep a static variable in a member function of a class that I have many objects of. I've had some trouble with it, and when I read up I found that such variables are static across all instances. Is there any way around this?
Would each instance of Foo create a new counter variable, or would it remain the same for all of them, i.e. baz.funky() would always use the same counter variable? What if the class was a template?
I am modifying a set of static variables inside of the class's member function. The static variables are private. An example of what I'm doing is as below,
utilities.h ----------- class utilities { private: static int num_nodes;
public: void parse_details(char* );
[Code] ....
I get a compilation error in the function void utilities::parse_details(char* filename)
which says: undefined reference to `utilities::num_nodes'
#include <iostream> class Hello { public: void Test() {
[Code].....
As i know a non-constant member function cant be called inside a constant member function but how the above code has been compiled successfully and giving the expected result .
What are the workarounds for accessing the non-static member variables of some class(Say A) inside static member functions of another class(Say B)? I am coding in c++. Class A is derived with public properties of class B. Any pointers?
So I have a class object that contains the private member variable spot and the public member function MoveLock. Within MoveLock, is a member variable called numbers that holds the place where a user is on a "lock knob". Now, what I'm trying to accomplish is that whenever the user turns the "knob" in the wrong direction, the position is updated with that current numbers so that the clicks needed to unlock the first state is also updated. But I get these errors:
Error E2096 C:Users...switchtest.cpp 34: Illegal structure operation in function main() Error E2294 C:Users...switchtest.cpp 39: Structure required on left side of . or .* in function main()
Ultimately, what I have in main() is a piece of what I'm going to implement in a class member function. I'm also thinking about moving the if else statements out of the for and creating a second one for the else portion.
Here's a part of my program. 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
Programe #1 // file.h class File { public: static const int var = 9; };
[Code]....
Program#1 is running fine, but program#2 gives linker error:
error LNK2005: "int GlobalVar" (?x@@3HA) already defined in file.obj
I know the header files are never compiled. Then in the above case, how the compiler knows the definition of variable var, but not able to find the definition of GlobalVar? What is the difference between this two programs?
WAVEFORMATEX InputTest::StandardWaveFormat { //Instantiate WaveFormat -- PCM standards StandardWaveFormat.wFormatTag = WAVE_FORMAT_PCM; StandardWaveFormat.cbSize = 0; //extra information sent over stream. Usually ignored in PCM format.
[Code] ....
I get the following errors starting with the header file:
Error1error C2146: syntax error : missing ';' before identifier 'StandardWaveFormat' Error2error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
both associated with the "const WAVEFORMATEX StandardWaveFormat; " line.
Here's a link to the WAVEFORMATEX struct: [URL] .....
Then the cpp source code is probably way off. Let me know if you'd like to see the errors associated with that.
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).
I am having trouble compiling my interface. I am trying to store a reference variable as a member variable of the interface object. Compiler says that the variable has not be initiated correctly.
LCD inherits from VisualInterface which is expecting a DisplayDriver object to be passed in (DisplayDriver is another interface, but thats not important).
I pass the displayDriver object in when LCD is instantiated in maininterfaces.zip
I was pasing it before as a pointer but was told that this could cause me problems with memory leaks and a reference was better, but now I cant seem to get it to compile.
I am getting this error invalid use of non static data member.my code looks something like this: i have a main.cpp and 2 class files with respective .h files, say one class file is named human (so i have human.cpp and human.h) and stats (so i have stats.cpp and stats.h) in my stats.h file, i have a double array: double HumanF[10][12] with everything filled in.then in my human.h file i just have a bunch of integers. human.cpp has formulas in it that use numbers from the double array i mentioned. for example
Human::Human() { constant (this is a double i made in human.h) = (1+Stats::HumanF[0][0]); i (another double) = pow(constant, ylvl); (ylvl is also an int I made in my header file) yhp = i*137; }
How does one use a functor as a static constexpr member? I had this basic functor for a class:
struct functor{ short operator()(char c)const{return c-'0';} };
And in the class, I use it as a static constexpr member: class Foo{ public: //... private: static constexpr functor k_funky = functor(); };
During the linking stage, I kept getting "undefined reference to 'Foo::k_funky'". So then I tried declaring the functor's constructor and operator function constexpr:
struct Speaker { static int numElem; string name; int number; // Phone string topic; float fee; };
// IN main() FUNCTION Speaker s[10];
The goal is for numElem to keep track of how many of the 10 elements are in use. However, I'm not sure the proper way to access the element, if it's even possible.
What am I doing wrong with static members and methods here?
compiler errors:
1>test.obj : error LNK2005: "private: static int Test::count" (?count@Test@@0HA) already defined in main.obj 1>c:usersjamesdocumentsvisual studio 2013Projectsstatic_testReleasestatic_test.exe : fatal error LNK1169: one or more multiply defined symbols found test.h #ifndef TEST_H_ #define TEST_H_ class Test {
I see many time where static data member is used to count creations of objects -
i.e.
1. the static data member is init to 0
2. the static data member is incremented by 1, in the Class' constructor, every time an object is created
However, if you define a global object of a class,
How can you tell that the static data member is initialized BEFORE the constructor of the global object is called? (i.e. before the global object is created).
Because to my understanding, you do not know in advance the order of global objects' creation -
so the Global Object could be created BEFORE the static data member was created and initialized.
"You cannot initialize the static data member in the class definition — that’s simply a blueprint for an object and initializing values for members are not allowed. You don’t want to initialize it in a constructor, because you want to increment it every time the constructor is called so the count of the number of objects created is accumulated."
Why don't you want to initialize it in a constructor?
Edit: Because every time it is called it will set it back to 0 or whatever the initializing value.