【发布时间】:2019-06-05 22:40:20
【问题描述】:
我有一个具有以下声明和随附定义的类:
friend ostream& operator<<(ostream& out, const Poly& poly);
ostream& operator<<(ostream& out, const Poly& poly) {}
和
private:
int *polyArray;
在该运算符函数的代码中,我有(除其他外):
if (poly.polyArray[i] != 0) {
out << poly.polyArray[i];
}
我从编译器 (Visual Studio) 中的下划线收到以下错误消息,特别是在“polyArray”下方:
int *Poly::polyArray
Member "Poly::polyArray" is inaccessible
我能够很好地调用公共成员函数,并且我认为我能够从朋友函数访问私有数据成员。
关于我为什么会收到此错误的任何想法?
注意: 根据要求,以下是完整课程的更多内容:
首先是头文件。
class Poly
{
public:
Poly(int coeff, int expon);
friend ostream& operator<<(ostream& out, const Poly& poly);
private:
int *polyArray;
int size;
};
然后是实现。
#include <iostream>
#include "Poly.h"
using namespace std;
Poly::Poly(int coeff, int expon) {
size = expon + 1;
polyArray = new int[size];
for (int i = 0; i < size; ++i) {
polyArray[i] = (i == expon ? coeff : 0);
}
}
ostream& operator<<(ostream& out, const Poly& poly) {
int currentSize = poly.getSize();
// If Poly is "empty", print 0
if (currentSize == 1 && poly.polyArray[0] == 0) {
out << 0;
return out;
}
for (int i = 0; i < currentSize; ++i) {
// Print the "+" sign if the coefficient is positive
//if (poly.polyArray[i] > 0) {
if (poly.polyArray[i] > 0) {
out << "+";
}
// Print the coefficient if it is not 0, skipping it and all following code otherwise
if (poly.polyArray[i] != 0) {
out << poly.polyArray[i];
}
else {
continue;
}
// Print "x" if the exponent is greater than 0
if (i > 0) {
out << "x";
}
// Print exponent if it is greater than 1
if (i > 1) {
out << "^" << i;
}
// Print a space if this is not the last term in the polynomial
if (i != currentSize - 1) {
out << " ";
}
}
return out;
}
最后,主要的。
#include "Poly.h"
#include <iostream>
using namespace std;
int main() {
Poly y(5, 7);
cout << y;
return 0;
}
【问题讨论】:
-
非常确定 - 我编辑了我的原始帖子以在声明旁边添加定义标题。我只是复制/粘贴它并没有改变任何东西。对我来说它看起来一样 - 我错过了什么吗?
-
Poly是否在命名空间范围内声明? -
Caleth,你是什么意思?
-
我发现了问题并更新了我的答案!