赞
踩
//函数声明
void ReadRanFile(CString szFilePath);
const CFvArray<CString>& GetPanelGrade() const { return m_fvArrayPanelGrade; }
//在另一个文件中调用ReadtRanFile这个函数
const CFsJudConfig& psJudConfig = m_pFsDefJudge->GetJudConfig();
psJudgeConfig.ReadRanFile(szFilePath); //报错!!
报错内容:cannot convert 'this' pointer from 'const CFsJudConfig' to 'CFsJudConfig&'
这就是因为:使用常量对象CFsJudConfig 调用了 非常量函数ReadRanFile()!
解决方法:
1.将普通成员函数 改为 常量成员函数
void ReadRanFile(CString szFilePath);=》void ReadRanFile(CString szFilePath) const;
(注意:1.1 此时,常量函数内部。常成员函数不能“更新/修改”类的成员变量,也不能调用该类中没有用const修饰的成员函数,只能调用常成员函数!
1.2 这个const函数是只读的,不可修改,而非const成员函数是可读可写的。)
2.重载一个GetJudConfig()方法
CFsJudConfig GetJudConfig() { return m_pFsDefJudge; }//const关键字可以用于对重载函数的区分
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
fun
const fun
也就是 type fun(class *this) const就相当于type fun(const class *this)
于是类中就能存在type fun()与type fun() const两个函数,也就是重载了fun函数
而普通指针能向常量指针转换而常量指针无法向普通指针转换。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
|
fun const
fun
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。