注册 登录
编程论坛 C++教室

&怎么用的

换空依晨 发布于 2014-03-04 20:04, 509 次点击
程序代码:
#include"iostream.h"
class cstudent
{
public:
friend ostream& operator<<(ostream& os,cstudent stu);
friend istream& operator>>(istream& is,cstudent& stu);
private:
char strname[10];
char strid[10];
int fscore[3];
};
ostream& operator<<(ostream &os,cstudent stu)
{
os<<endl<<"请输入学生信息:"<<endl<<"姓名"<<stu.strname<<endl<<"学号"<<stu.strid<<endl;
os<<"三门成绩为:"<<stu.fscore[0]<<"\t"<<stu.fscore[1]<<"\t"<<stu.fscore[2]<<endl;
return os;
}
istream& operator>>(istream& is,cstudent& stu)
{
cout<<"请输入学生信息:"<<endl<<"姓名";
is>>stu.strname;
cout<<"学号:";
is>>stu.strid;
cout<<"三门成绩";
is>>stu.fscore[0]>>stu.fscore[1]>>stu.fscore[2];
return is;
}
void main()
{
cstudent one ;
cin>>one;
cout<<one;
}

friend ostream& operator<<(ostream& os,cstudent stu);
friend istream& operator>>(istream& is,cstudent& stu);这两个定义为什么不一样 ,多了个& ,还有这里面的所有&的位置到底是怎么放的 怎么书上有放在左 放在右 ,但是我换个位置 编译没错误 运行就不行啊
4 回复
#2
rjsp2014-03-05 08:56
连引用这种C++最基础的知识点都不知道,还是先看书吧。
我来回答你有意义的问题,比如“怎么书上有放在左 放在右”,答:放哪边都可以,在语法层面上它俩无任何差别。但正常都放在左边,比如 cstudent& stu,左部分 cstudent& 是类型,右部分 stu 是定义的变量名(注:C++不建议一行多个定义,即如果你一定要一行多个定义,只能放右边了,如 cstudent &stu1, &stu2, &stu3;)。
而如果放右边,即 cstudent &stu,是很别扭的,因为 &stu 是个无意的东西,这和 int *p 等不一样。
(注:C语言中习惯写成int *p,以突出*p的类型为int;C++语言中习惯写成int* p,以突出p的类型为int*。当然,两者本质是一样的。而对于cstudent &stu1在C++中就说不通了,所以C++非变态的写法都是cstudent& stu1。只有一些长期写C代码,后来转成写C++代码的人,其顽固习性还没改过来。)

最后问一下,你的这代码是书上的吗?如果是,这本书真不能看了
a. C++中早就废弃 "iostream.h" 了
b. C/C++中从来没说过main函数返回类型可以为void
以上两点还是小事,而它竟然在friend函数前加public,凭这行为推断其智力,今生是无法学会C/C++了,所以你不要被这本书给骗废了。
#3
换空依晨2014-03-05 10:03
回复 2楼 rjsp
friend ostream& operator<<(ostream& os,cstudent stu);
friend istream& operator>>(istream& is,cstudent& stu);为什么这两个友元定义不一样  下边的怎么多了个&
#4
rjsp2014-03-05 10:33
operator<< 不需要修改 stu, operator>> 需要修改

BTW: 对于你这个复杂的cstudent,
friend ostream& operator<<(ostream& os,const cstudent& stu);

friend ostream& operator<<(ostream& os,cstudent stu);
好.
你还是换本书吧。
#5
peach54602014-03-05 10:52
以下是引用rjsp在2014-3-5 08:56:24的发言:

连引用这种C++最基础的知识点都不知道,还是先看书吧。
我来回答你有意义的问题,比如“怎么书上有放在左 放在右”,答:放哪边都可以,在语法层面上它俩无任何差别。但正常都放在左边,比如 cstudent& stu,左部分 cstudent& 是类型,右部分 stu 是定义的变量名(注:C++不建议一行多个定义,即如果你一定要一行多个定义,只能放右边了,如 cstudent &stu1, &stu2, &stu3;)。
而如果放右边,即 cstudent &stu,是很别扭的,因为 &stu 是个无意的东西,这和 int *p 等不一样。
(注:C语言中习惯写成int *p,以突出*p的类型为int;C++语言中习惯写成int* p,以突出p的类型为int*。当然,两者本质是一样的。而对于cstudent &stu1在C++中就说不通了,所以C++非变态的写法都是cstudent& stu1。只有一些长期写C代码,后来转成写C++代码的人,其顽固习性还没改过来。)

最后问一下,你的这代码是书上的吗?如果是,这本书真不能看了
a. C++中早就废弃 "iostream.h" 了
b. C/C++中从来没说过main函数返回类型可以为void
以上两点还是小事,而它竟然在friend函数前加public,凭这行为推断其智力,今生是无法学会C/C++了,所以你不要被这本书给骗废了。

+1
第一次看到public的友元
惊为天人...
瞬间被吓尿了...
1