[英]Friend ostream& operator<< can't access private member
Roughly, this is what my code looks like: 大致来说,这就是我的代码:
template<typename K, typename V>
class A{
private:
size_t num_;
public:
A(initializer_list< something<K,V> > smthng);
friend ostream& operator<<(ostream &out, const A &as){
size_t number = num_;
};
};
template<typename K, typename V>
A<K,V>::A(initializer_list< something<K,V> > smthng){
size_t sz = 5;
num_ = sz;
}
For some reason my code will always give "error: invalid use of non-static data member" as an error when I attempt to compile. 由于某种原因,当我尝试编译时,我的代码将始终将“错误:无效使用非静态数据成员”作为错误。 Obviously the code above isn't what I have exactly, but this is the only error I'm getting.
显然,上面的代码不是我确切拥有的,但这是我遇到的唯一错误。 I thought the benefit of using the friend function wasa thaat you can access private members, but I can't seem to do so.
我以为使用好友功能的好处是可以访问私有成员,但我似乎做不到。
A friend function is an external function wrt the class you are defining it in. You can access private members, but you have no this
pointer available. 朋友函数是使用您要在其中定义类的外部函数。您可以访问私有成员,但没有
this
指针可用。
Threfore, you should change 因此,您应该更改
size_t number = num_;
with 与
size_t number = as.num_;
inside the operator<<()
implementation. 在
operator<<()
实现中。
As it currently stands, you are using the num_ variable as if it were a static member variable, that is, as if it does not belong to a particular object of a class but belongs to the class as a whole. 就目前而言,您正在使用num_变量,就好像它是一个静态成员变量一样,也就是说,好像它不属于某个类的特定对象而是属于整个类。 What you need to do is to indicate the object whose private member variable num_ you need to access via you << operator.
您需要做的是指示需要通过<<操作符访问其私有成员变量num_的对象。 You need to do:
您需要做:
class A{
private:
int num_;
public:
A();
friend std::ostream& operator<<(std::ostream &out, const A &as)
{
int number = as.num_;
out << number << std::endl;
}
};
A::A()
{
int sz = 5;
num_ = sz;
}
int main()
{
A object;
std::cout << object << std::endl;
return 0;
}
This works fine for me. 这对我来说很好。 Try to compile this as it is and you will see it displaying 5 on the console without errors.
尝试按原样进行编译,您会在控制台上看到无错误显示5。 The segmentation fault is probably due to another error on your code.
分段错误可能是由于代码上的另一个错误。
I have same issue with the operator, it is not accessing the private members of the class. 我对运算符有同样的问题,它没有访问该类的私有成员。
class X {
char* xName;
double dd;
public:
X(char*, double);
X(const X&);
~X();
X& operator=(const X&);
friend ostream& operator<<(ostream&, X&);
};
//in cpp
ostream& operator<<(ostream& o, X& obj) {
/*when i try the following i have error msg saying that private member xName is
inaccessible*/
o>> obj.xName >> endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.