Reputation: 1576
Zombie.h has some static member variables. Read.cpp, which includes Zombie.h, knows the values that need to go in those variables. I want read.cpp to set those variables with something along the lines of
int Zombie::myStaticInt = 4;
or
Zombie::setStaticVar(4);
I've tried everything I can think of, including using a public static accessor function and even making the static variables themselves public, but I've been getting a lot of "undefined reference" or "invalid use of qualified-name" errors. By looking into those I found out how to set Zombie.h's private static member variables from Zombie.cpp, but I don't have a Zombie.cpp file, just read.cpp. Can I set them from Read.cpp instead, and if so, how?
// In Zombie.h
class Zombie {
public:
static void setMax(int a_in, int b_in, int c_in) {
a = a_in;
b = b_in;
c = c_in;
}
private:
static int a, b, c;
}
// In read.cpp
#include "Zombie.h"
...
main() {
int Zombie::a; // SOLUTION: Put this outside the scope of main and other functions
int Zombie::b; // SOLUTION: Put this outside the scope of main and other functions
int Zombie::c; // SOLUTION: Put this outside the scope of main and other functions
int first = rand() * 10 // Just an example
int second = rand() * 10 // Just an example
int third = rand() * 10 // Just an example
Zombie::setMax(first, second, third);
return 0;
}
This yields (Updated) (Move first three lines of main outside of main() to solve this)
invalid use of qualified-name 'Zombie::a'
invalid use of qualified-name 'Zombie::b'
invalid use of qualified-name 'Zombie::c'
Upvotes: 0
Views: 1130
Reputation: 135
Your problem is you haven't implemented Zombie class yet. Your code here:
zombie.h
#ifndef ZBE_H
#define ZBE_H
class Zombie
{
public:
static int myStaticInt;
Zombie();
};
#endif
read.cpp
#include <stdio.h>
#include <iostream>
#include "zombie.h"
int Zombie::myStaticInt = 1;
Zombie::Zombie()
{
}
int main()
{
cout << "OOOK: " << Zombie::myStaticInt << endl;
Zombie::myStaticInt = 100;
cout << "OOOK: " << Zombie::myStaticInt << endl;
return 0;
}
Upvotes: 0
Reputation: 310883
You have to define a,b,c
somewhere. So far you've only declared them to exist. In some .cpp file, at the outer scope, you need to add:
int Zombie::a;
int Zombie::b;
int Zombie::c;
EDIT Re your edit, you can't put them inside a method. You have to put this at the outermost scope of the .cpp file.
Upvotes: 2
Reputation: 308138
Unlike non-static variables that get storage allocated in every object, static variables must have their storage outside of the class. You do this by creating definitions for the variables in a .cpp file. It doesn't matter which file they go in, although for convenience they should go with the code for the class.
int Zombie::a;
int Zombie::b;
int Zombie::c;
The linker error you're getting is telling you that these lines are missing.
Upvotes: 1