I know how to get this done in Java, but I can't figure out how to do it in C++ Here is my questions: I have a class called "stack" and I create different Objects from stack class in my main method. I want to store a variable in the stack class, so all the Object can access the variable. My header file:
Template<class Item>
struct stackLinked{
Item value;
stackLinked* next;
}
Template<class T>
class stack{
public:
static int stored;
.......
.......
private:
.......
}
My main function:
stack<T> temp;
temp.stored=1;
stack<T> numbers;
stack<T> operations;
................
When I stored the value into temp, can numbers and operations have the same variable (same value)?
Yes. Static variable is one for all instances of stack
. Every instance has access to the one and same static variable.
Example:
#include <iostream>
using namespace std;
class stack{
public:
static int stored;
};
int stack::stored; // definition of static variable, necessary
int main() {
// your code goes here
stack s, m, n;
s.stored = 4;
std::cout << s.stored << "," << m.stored << "," << n.stored << std::endl;
m.stored = 5;
std::cout << s.stored << "," << m.stored << "," << n.stored << std::endl;
n.stored = 1;
std::cout << s.stored << "," << m.stored << "," << n.stored << std::endl;
return 0;
}
output:
4,4,4
5,5,5
1,1,1
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments