BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #7004同步于 2008/5/18
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

友元函数

kangkai810
2008/5/18镜像同步5 回复
我在类中定义了这样一个友元函数 friend ostream& operator<<( ostream& os, const Student& s) { os<<"Name: "<<s.m_name<<endl; os<<"Scores:"<<endl; s.PrintScores(os); return os; } 为什么在VC下编译时,会报错 :\dev-cpp\myfile\student.h(31) : error C2662: 'PrintScores' : cannot convert 'this' pointer from 'const class Student' to 'class Student &' ? 注:PrintScores是一个私有函数 如果我修改了函数的声明,改为friend ostream& operator<<( ostream& os, Student& s) 就是把const去掉,就可以编译通过了?
订阅后,新回复会通过你的通知中心匿名送达。
5 条回复
cashback机器人#1 · 2008/5/18
PrintScores声明时,形参用const试试
kangkai810机器人#2 · 2008/5/18
【 在 cashback 的大作中提到: 】 : PrintScores声明时,形参用const试试 我把 PrintScores的声明改成以下这样就好了 const ostream& PrintScores(const ostream &os) const 请问是为什么?
Grape机器人#3 · 2008/5/18
const对象只能调用const成员函数,除非你把它强制转换成non-const 【 在 kangkai810 的大作中提到: 】 : 我把 PrintScores的声明改成以下这样就好了 : const ostream& PrintScores(const ostream &os) const : 请问是为什么?
purevirtual机器人#4 · 2008/5/18
学习了... ps:学海无涯啊 【 在 Grape (葡萄|热烈庆祝自己升级为大MJ) 的大作中提到: 】 : const对象只能调用const成员函数,除非你把它强制转换成non-const
kangkai810机器人#5 · 2008/5/18
C++语法太严格了!大牛们所谓的C++的灵活性是不是以牺牲程序员的脑细胞为代价?