【问题标题】:cannot access protected member declared in class from a friend function in derived class无法从派生类中的友元函数访问类中声明的受保护成员
【发布时间】:2015-02-27 16:09:41
【问题描述】:

我有一个基类如下:

//基类-arrayListType.h

class arrayListType
{
public:
//some function members;

protected:
elemType *list;
int length;
int maxSize;
};

然后是派生类:

//派生类-polynomialType.h

#include "arrayListType.h"

class polynomialType: public arrayListType<double>
{
friend ostream& operator<<(ostream& ,const polynomialType&);
friend istream& operator>>(istream& ,polynomialType&);

public:
polynomialType operator+(const polynomialType&);
polynomialType operator-(const polynomialType&);
//polynomialType operator*(const polynomialType&);
double operator() (double x);
polynomialType(int size = 100);
int min(int x,int y) const;
int max(int x,int y) const;
};

但是编译代码后,我得到了错误:

error C2248: 'arrayListType<elemType>::length' : cannot access protected member declared in class 'arrayListType<elemType>'

我已经搜索了解决方案,但找不到,请帮助。 运算符>>的定义供参考;

istream& operator>>(istream is,polynomialType& p)
{
cout << "the degree of this polynomial is" << p.length-1 << endl;

for (int i = 0; i < p.length; i++)
{
    cout << "enter coefficient of x^" << i <<": ";
    is >> p.list[i];
}
return is;
}

该错误仅显示朋友功能,为什么会这样??

【问题讨论】:

  • 您是否尝试过将friend 函数放在您的public: 定义下?
  • friend 声明不需要在任何特定的访问修饰符下。

标签: c++ inheritance friend


【解决方案1】:
friend istream& operator>>(istream& ,polynomialType&);

诗句

istream& operator>>(istream is,polynomialType& p)

您的流函数忘记了引用运算符&amp;,因此具有不同的函数签名。不仅如此,它还可能导致细微的错误,例如复制流对象(可能有也可能没有额外的副作用)而不是重用它。

【讨论】:

  • 流不可复制;这里唯一可能发生的事情就是将流移入(很难不注意到)。
  • 确实,STL 流是不可复制的;非标准流可能是可复制的。如果没有 ::std:: 完全限定标识符,命名空间问题可能会导致 istream 解析为同名的自定义类型。
猜你喜欢
  • 1970-01-01
  • 2013-10-21
  • 2015-12-30
  • 2012-08-29
  • 2016-04-07
  • 2019-01-20
  • 2016-02-29
  • 2012-05-02
  • 2014-08-27
相关资源
最近更新 更多