无法从派生类中的友元函数访问类中声明的受保护成员

时间:2014-12-31 15:52:18

标签: c++ inheritance friend

我有一个基类如下:

// base class- arrayListType.h

class arrayListType
{
public:
//some function members;

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

然后是派生类:

// derived class-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>'

我搜索了解决方案,但找不到,请帮忙。 运营商的定义&gt;&gt;给予参考;

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;
}

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

1 个答案:

答案 0 :(得分:1)

friend istream& operator>>(istream& ,polynomialType&);

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

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

相关问题