Reputation: 1069
I started studying classes and now I faced a problem. I'm trying to put all my variables into a class, but I get errors:
main.cpp|6|error: expected identifier before string constant|
main.cpp|6|error: expected ',' or '...' before string constant|
main.cpp|7|error: expected identifier before string constant|
main.cpp|7|error: expected ',' or '...' before string constant|
Although when I make them global everything works fine
class Kauliukas{
ifstream inFile("inFile.in");
ofstream outFile("outFile.out");
int n, akutes[100],k=0;
void ivedimas();
void skaiciavimas();
void isvedimas();
};
What's the problem?
Upvotes: 1
Views: 10103
Reputation: 31577
In pre-C++11 versions of the language you can only declare variables inside the class body, you can't also initialize them (ifstream inFile
is a declaration; ifstream inFile("infile.in")
is a declaration and an initialization).
You have to do it like this:
class Kauliukas
{
public:
Kauliukas();
private:
ifstream inFile;
};
Kauliukas::Kauliukas() // This is the constructor definition
: inFile("infile.in") // This is called an initialization list
{
// ...
}
Upvotes: 2
Reputation: 60014
Initialization goes in the constructor. That's different than, for instance, C#. You must define a constructor like
class Kauliukas {
public:
Kauliukas() : inFile("inFile.in"), outFile("outFile.out"), k(0) {}
private:
ifstream inFile;
ofstream outFile;
int n, akutes[100],k;
void ivedimas();
void skaiciavimas();
void isvedimas();
};
Upvotes: 6