Using classes in function outside main
Please help me figure out what I'm doing wrong.
I have a class, declared in a header file:
Code:
// std_dice.h
// header file for standard system include files,
// project include files
#include <stdio.h>
#include <tchar.h>
// additional headers
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <time.h>
namespace DICE {
class SingleDie {
public:
int nRolled;
public:
void RollDie();
};
}
void fStupidFunction();
Also declared was a stupid little function, to be used in main. It replaces a larger function, for the question, that was / is going to collect some statistics about rolled dice.
Here is main.cpp, including the class definition, the main function, and the function where I can't properly use the class.
Code:
// main.cpp
#include "std_dice.h"
using namespace std;
int main(){
/***************Classes here********************************/
// set up the SingleDie class
class SingleDie {
public:
int nRolled;
// constructor
SingleDie() {
cout << "Constructor performed \n\n"; // for testing
nRolled = 0;
} // SingleDie constructor
public:
void RollDie() {
nRolled = 1;
nRolled = 10 + rand() % 60;
nRolled /= 10;
} // RollDie
}; //SingleDie class
/***************Main testing here*******************************************/
using namespace DICE;
SingleDie ssss;
ssss.RollDie();
cout << ssss.nRolled << " = Value of nRolled in main \n\n";
fStupidFunction();
// pause after executing console application
system("PAUSE");
return EXIT_SUCCESS;
return 0;
}//main
/*********************Functions Here****************************/
void fStupidFunction() {
//using namespace DICE;
DICE::SingleDie sOneDice;
sOneDice.nRolled = 7; // Works: member variable is public for now
sOneDice.RollDie(); // Doesn't work!
// If I comment out the above line, the program compiles.
cout << sOneDice.nRolled << " In the stupid little function! \n\n";
};
As per the comments in the function: fStupidFunction: I can access the member variable .nRolled just fine. (I'll later fix the class so that there is a member function to set .nRolled, make it private, and make sure it never gets set to 7.)
In fact, if I comment out the line SOneDice.RollDie(); then the program compiles and runs. Therefore, I can suppose that my namespace is okay and that the class variable is declared okay--or can I? The problem comes when I try to use the member function RollDie().
RollDie() works in main but not in fStupidFunction.
It doesn't make sense to me that one cannot use a class variable in a function--only in main. I've looked in Bjarne's book (which is way above my head anyway), in C++ for Dummies (which doesn't cover the issue), and in various tutorials. If someone can help me to understand what I've done wrong and how to fix it, I would be very appreciative.
Thanks,
Keith