返回信息流在VC6.0中编译cpp文件时提示(红色为出错行):
error C2248: 'real' : cannot access private member declared in class 'complex'
see declaration of 'real'
error C2248: 'imaginary' : cannot access private member declared in class 'complex'
see declaration of 'imaginary'
//头文件complex0.h
#ifndef COMPLEX0_H_
#define COMPLEX0_H_
#include <iostream>
#include <StdAfx.h>
using namespace std;
class complex
{
private:
double real;
double imaginary;
public:
complex();
complex(const double & n1,const double & n2);
~complex();
double realval()const{return real;}
double imagval()const{return imaginary;}
complex operator+(const complex & b)const;
complex operator-(const complex & b)const;
complex operator*(const complex & b)const;
complex operator~();
friend istream & operator>>(istream & is, complex & b);
friend ostream & operator<<(ostream & os,const complex & b);
friend complex operator*(const double & n,const complex & b);
};
#endif
*****************************************************
//CPP文件
#include "complex0.h"
using namespace std;
complex::complex()
{
real=imaginary=0.0;
}
complex::complex(const double & n1,const double & n2)
{
real=n1;
imaginary=n2;
}
complex::~complex()
{
}
complex complex::operator+(const complex & b)const
{
return complex(real+b.real,imaginary+b.imaginary);
}
complex complex::operator-(const complex & b)const
{
return complex(real-b.real,imaginary-b.imaginary);
}
complex complex::operator*(const complex & b)const
{
return complex(real*b.real-imaginary*b.imaginary,real*b.imaginary+imaginary*b.real);
}
complex complex::operator~()
{
return complex(real,-imaginary);
}
istream & operator>>(istream & is, complex & b)
{
is>>b.real>>b.imaginary;
return is;
}
ostream & operator<<(ostream & os,const complex & b)
{
os<<b.realval(),b.imagval();
return os;
}
complex operator*(const double & n,const complex & b)
{
return complex(n*b.real,n*b.imaginary);
}
*****************************************************
//测试文件
#include <iostream>
#include "complex0.h"
using namespace std;
int main()
{
complex a (3.0,4.0);
complex c;
cout<<"Enter a complex number(q to quit): \n";
while(cin>>c)
{
cout<<"c is "<<c<<'\n';
cout<<"complex conjugate is "<<~c<<endl;
cout<<"a is "<<a<<endl;
cout<<"a+c is"<<a+c<<endl;
cout<<"a-c is"<<a-c<<endl;
cout<<"a*c is"<<a*c<<'\n';
cout<<"2*c is"<<2*c<<endl;
cout<<"Enter a complex number(q to quit): \n";
}
cout<<"Bye!\n";
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #29617同步于 2009/10/10
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
[求助]重载输入操作符时的问题 不知错在哪里
zgslovewy
2009/10/10镜像同步7 回复
订阅后,新回复会通过你的通知中心匿名送达。
7 条回复
我怎么没发现有错……
E:\cs\programming>g++ main.cpp complex.cpp -o run.exe
E:\cs\programming>run.exe
Enter a complex number(q to quit):
1+2i
c is 1
complex conjugate is 1
a is 3
a+c is4
a-c is2
a*c is-5
2*c is2
Enter a complex number(q to quit):
Bye!