I have a class with a private static variable. The main function should change the value in the variable, but even if I set the main function as a friend of the class the compiler tells me that the variable is private and not accessible from main.
Example:
ClassA.h:
namespace nameA{
class ClassA {
private:
static int varA;
public:
ClassA(){};
friend int main(void);
};
}
ClassA.cpp:
namespace nameA{
int ClassA::varA = 0;
}
main:
int main(void){
ClassA::varA = 42; //ERROR
}
I don't know if "friend" also allows access to static members or if I have to find another solution.
It because friend function main
in ClassA is located in nameA
namespace.
If you want to declare as friend the int main(void)
function, that located in global scope, you should do it this way:
friend int ::main(void);
Whole source (compiled in VS2015):
int main(void);
namespace nameA {
class ClassA {
private:
static int varA;
public:
ClassA() {};
friend int ::main(void);
};
}
namespace nameA {
int ClassA::varA = 0;
}
int main(void) {
nameA::ClassA::varA = 42;
return 0;
}
Your friend
declarations grants friendship to a function named main
in the namespace nameA
, not the global main
function.
Your code is equivalent to
namespace nameA
{
int main(void);
class classA
{
...
friend int main(void);
};
}
You need to declare main
before the namespace starts.
int main(void);
namespace nameA
{
class classA
{
...
friend int main(void);
};
}
should work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With