请问这个代码有什么问题?
mcmay 2015-03-26 02:49:00 下面的代码主要是重载一个除法运算符和一个<<操作符,但编译后却说私有数据出错。我看不出哪里侵犯了私有数据。
麻烦看看错在哪里,谢谢。
代码如下:
div.h文件:
#ifndef DIV_H_
#define DIV_H_
#include <iostream>
// class prototypes
class Divisor {
double x;
double y;
public:
Divisor();
Divisor(double a, double b);
~Divisor();
void GetValue();
Divisor operator/(double n) const;
friend Divisor operator/(double n, Divisor & div);
friend std::ostream & operator<<(std::ostream & ot, Divisor & div);
};
#endif
div.cpp文件
// functions
#include <iostream>
#include "div.h"
using namespace std;
Divisor::Divisor()
{
x = y = 0;
}
Divisor::Divisor(double a, double b)
{
x = a;
y = b;
}
Divisor::~Divisor()
{
}
void Divisor::GetValue()
{
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
}
Divisor Divisor::operator/(double n) const
{
Divisor temp;
if (!n)
{
cout << "Divisor is zero. Setting n to 1.\n";
n = 1;
}
temp.x = x / n;
temp.y = y / n;
return temp;
}
Divisor operator/(double n, Divisor & div)
{
Divisor temp;
if (!div.x || !div.y)
{
cout << "One of the divisor is zero. Setting it to 1.\n";
if (!div.x)
div.x = 1;
else
div.y = 1;
}
temp.x = n / div.x;
temp.y = n / div.y;
return temp;
}
ostream & operator<<(ostream & ot, const Divisor & div)
{
ot << div.x << " " << div.y << endl;
return ot;
}
main.cpp文件
// main.cpp
#include <iostream>
#include "div.h"
int main()
{
using namespace std;
Divisor ds(5, 6);
Divisor dt;
double p;
cout << "Enter divisor: ";
cin >> p;
dt = ds / p;
cout << dt << endl;
ds.GetValue();
dt = p / ds;
cout << dt << endl;
return 0;
}
编译器信息如下:
In file included from /storage/emulated/0/AA/za/div/div.cpp:3:0:
/storage/emulated/0/AA/za/div/div.h: In function 'std::ostream & operator<<(std::ostream &, const Divisor&)':
/storage/emulated/0/AA/za/div/div.h:9:9: error: 'double Divisor::x' is private
double x;
^
compilation terminated due to -Wfatal-errors.