I
Immortal Nephi
I tried to add const to the global function. It becomes friend with
class A. Friend allows global function to modify private data
member. Need to add const and prevent global function from modifying
data member.
Why did C++ Compiler give error like C2662? No const added is
allowed. Explain? What is another solution?
class A
{
public:
A() {}
~A() {}
friend void Test( const A &r );
void Run()
{
Test( *this );
}
private:
int m_a;
int get_a()
{
return m_a;
}
};
void Test( const A &r ) // add const?
{
r.get_a(); // OK
r.m_a = 2; // should compile with error
}
int main()
{
A a;
a.Run();
return 0;
}
class A. Friend allows global function to modify private data
member. Need to add const and prevent global function from modifying
data member.
Why did C++ Compiler give error like C2662? No const added is
allowed. Explain? What is another solution?
class A
{
public:
A() {}
~A() {}
friend void Test( const A &r );
void Run()
{
Test( *this );
}
private:
int m_a;
int get_a()
{
return m_a;
}
};
void Test( const A &r ) // add const?
{
r.get_a(); // OK
r.m_a = 2; // should compile with error
}
int main()
{
A a;
a.Run();
return 0;
}