| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 884 人关注过本帖
标题:[讨论]友元与标准名空间矛盾问题
取消只看楼主 加入收藏
weishj
Rank: 1
等 级:新手上路
威 望:2
帖 子:141
专家分:0
注 册:2007-4-22
收藏
 问题点数:0 回复次数:2 
[讨论]友元与标准名空间矛盾问题

VC++6.0中存在使用了标准名空间后友元函数不能访问类私有成员的问题,但恰恰有些东西不使用标准名空间会出现问题,如果即要使用友元函数,又想使用比如string类的内容,就会出现一系列问题,下面举个例子,其代码来自解一元二次方程那个帖子,我重载了>>操作符只是为了说明这个问题,并没什么实际使用价值,其测试部分也没写
/************若这样,则编译时无法使用string类************************/
#include <iostream.h>
#include <math.h>
#include <string.h>
//using namespace std;
/*******************************************************************/
/**********************若按下面,则友元函数无法访问私有成员**********/
/*
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
*/
class funtion
{
public:
~funtion(){cout<<"求解完毕"<<endl;}
void set_value(); //输入函数
void display(); //求解函数
void show_value();//输出函数
friend istream& operator >>(istream& ins,funtion& f);
private:
float a;
float b;
float c;
float x1;
float x2;
float r;
float i;
float pd;
};
istream& operator >>(istream& ins,funtion& f)
{
string str[3];
//ax^2+bx+c=0
IfError:
ins>>f.a>>str[0]>>f.b>>str[1]>>f.c>>str[2];
if(0==a || "x^2+"!=str[0] || "x+"!=str[1] || "=0"!=str[2])
{
cerr<<"输入错误,请输入方程(ax^2+bx+c=0)"<<endl;
ins.ignore();
ins.clear();
goto IfError;
}
return ins;
}
void funtion::set_value ()
{
cout<<"输入 a b c 的值且 a b c 不可全为零"<<endl;
cin>>a;
cin>>b;
cin>>c;
}
void funtion::display ()
{
pd=b*b-4*a*c;
if(pd>0)
{
x1=-b/(2*a)+sqrt(pd)/(2*a);
x2=-b/(2*a)-sqrt(pd)/(2*a);
}
else if(pd==0)
{
x1=-b/(2*a);
x2=-b/(2*a);
}
else
{
r=-b/(2*a);
i=sqrt(-pd)/(2*a);
}
}
void funtion::show_value ()
{

if(pd>0)
cout<<"x1="<<x1<<" "<<"x2="<<x2<<endl;
else if(pd==0)
cout<<"x1="<<x1<<" "<<"x2="<<x2<<endl;
else
cout<<"x1="<<r<<'+'<<i<<"i"<<" "<<"x2="<<r<<'+'<<i<<"i"<<endl;
}
int main()
{
funtion f;
f.set_value ();
f.display ();
f.show_value ();
return 0;
}
这问题谁帮提供个解决思路,谢谢!

[此贴子已经被作者于2007-5-6 10:44:45编辑过]

搜索更多相关主题的帖子: 友元 标准名 用友 空间 string 
2007-05-05 23:19
weishj
Rank: 1
等 级:新手上路
威 望:2
帖 子:141
专家分:0
注 册:2007-4-22
收藏
得分:0 

If you shed tears when you miss the sun, you also miss the stars.
2007-05-05 23:38
weishj
Rank: 1
等 级:新手上路
威 望:2
帖 子:141
专家分:0
注 册:2007-4-22
收藏
得分:0 
版主说的有理,至此可不再讨论,结贴

If you shed tears when you miss the sun, you also miss the stars.
2007-05-06 10:45
快速回复:[讨论]友元与标准名空间矛盾问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.012206 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved