In the following code I am trying to have a friend function access the private member of the class. To my understanding I am correctly declaring it as a friend function, but VS2012 is giving me the error:
error C2248: 'X::S::s_' : cannot access private member declared in class 'X::S'
Can anyone suggest what I am doing wrong? This is the simplest example that demonstrates the compiler error that I could come up with.
namespace X
{
class S
{
friend std::string r(X::S &s);
std::unique_ptr<std::istream> s_;
};
}
std::string r(X::S &s)
{
auto& x = s.s_;
return "";
}
You're defining ::r
, not X::r
, which is what your friend declaration is for. Move the function into the namespace alongside the class, or define it right inside the class, though that can be problematic with a class template or keeping the class definition concise. If the definition is in a separate file, you can still enclose it with the namespace like you do the class to add it to the namespace. I would also suggest removing the X::
qualification as it's already in X
.
namespace X
{
class S
{
friend std::string r(S &s);
std::unique_ptr<std::istream> s_;
};
std::string r(S &s)
{
auto& x = s.s_;
return "";
}
}
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