div 占用剩余高度:C++"高手"请进,帮小弟一个小忙!!

来源:百度文库 编辑:高校问答 时间:2024/04/24 20:48:43
~~我学习了重载函数后,想自己实践一下,于是随便编了个程序来实验,见下文:
#include <iostream>
using namespace std;
class ts
{
public:
ts();
friend ts &operator>>(istream &in,ts &t); //声明重载
int get_m(); //返回私有变量
private:
int m;
};

ts::ts()
{
m=0;
}

ts &operator>>(istream &in,ts &t) //重载函数体
{
in>>m;
if(m<10) m=0; //条件判断
}

int get_m()
{
return m;
}
int main(void)
{
ts tt;
cin>>tt; //重载运算符调用

cout<<tt.get_m()<<endl;
return 1;
}
这是程序出错信息:
--------------------Configuration: A_TEST - Win32 Debug--------------------
Compiling...
输入符重载测试.cpp
E:\MATE\VC\A_TEST\输入符重载测试.cpp(20) : error C2065: 'm' : undeclared identifier
E:\MATE\VC\A_TEST\输入符重载测试.cpp(31) : error C2593: 'operator >>' is ambiguous
执行 cl.exe 时出错.

输入符重载测试.obj - 1 error(s), 0 warning(s)
|
|
|
根据提示我能知道是我定义友元函数出错,因为在调用"tt."时并没有运算符重载函数,而我又不知怎么调试,希望哪位好心人自己调试一下,给我可行的程序,并说明出错原因,谢谢!!
|
|
|
in>>m;
这一句为什么会提醒出错,是不是格式错了!要如何修改!!

1. 我不习惯用名字空间,而且会出现重载符号编译器二义性的事情,确实困惑我不少时间。
2。get_m是成员函数,所以在定义时用:int ts::get_m(){...}
3. friend ts &operator>>(istream &in,ts &t);是友元函数,
所以in>>t.m; if(t.m<10) t.m=0; 等必须加上对象名t.
4. 上面友元函数必须要有返回值
5。上面友元函数定义不符合常规,应该是:
friend istream &operator>>(istream &in,ts &t);

#include <iostream.H>
class ts
{
public:
ts();
friend ts &operator>>(istream &in,ts &t); //声明重载
int get_m(); //返回私有变量
private:
int m;
};

ts::ts()
{
m=0;
}

ts &operator>>(istream &in,ts &t) //重载函数体
{
in>>t.m;
if(t.m<10) t.m=0; //条件判断
return t;
}

int ts:: get_m()
{
return m;
}
int main(void)
{
ts tt;
cin>>tt; //重载运算符调用

cout<<tt.get_m()<<endl;
return 1;
}

是的