[ACCEPTED]-C++ - Private variables in classes-private
You forgot to write TestClass::
as shown below:
void TestClass::set(string x)
//^^^^^^^^^^^this
void TestClass::print(int x)
//^^^^^^^^^^^this
That 5 is necessary so that compiler can know that 4 set
and print
are member functions of class TestClass
. And 3 once you write it, making them member functions, they 2 can acess the private members of the class.
Also, without 1 TestClass::, set
and print
function would become free functions.
Use
void TestClass::set(string x){
and
void TestClass::print(int x){
0
In your .cpp
file, you need to make the set 2 and print member functions explicitly part 1 of the class, like:
void TestClass::set(string x){
hi = x;
}
void TestClass::print(int x){
if(x == 2)
cout << hi << " x = two\n";
else if(x < -10)
cout << hi << " x < -10\n";
else if(x >= 10)
cout << hi << " x >= 10\n";
else
cout << hi << " x = " << x << endl;
}
You don't scope resolve your print
and set
functions 1 with the class name.
void TestClass::set(string x){
hi = x;
}
void TestClass::print(int x){
if(x == 2)
cout << hi << " x = two\n";
else if(x < -10)
cout << hi << " x < -10\n";
else if(x >= 10)
cout << hi << " x >= 10\n";
else
cout << hi << " x = " << x << endl;
}
say
void TestClass::set(string x){
instead of
void set(string x){
same for print(). You declared 2 them as global functions instead of member 1 functions of TestClass.
Your methods are not defined as methods 2 of the class. Try using TestClass::set and 1 TestClass::print.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.