文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>常引用函数重载

常引用函数重载

时间:2010-09-04  来源:代码438300

这个问题是我在OpenGL论坛里看到的,http://forum.glframe.com/viewtopic.php?f=17&t=28,大概这个人想把 set()函数和 get() 函数统一为一个函数,但是创建的常对象来调用这个函数时出错了:

代码

 1 #include<iostream>
2
3 class Test{
4 public:
5 int& assign() {
6 return x;
7 }
8 int mult() {
9 return 2*x;
10 }
11 private:
12 int x;
13 };
14 int main(){
15 Test t;
16 t.assign()=8;
17 std::cout<<t.mult()<<std::endl;
18 Test& t1=t;
19 t1.assign()=9;
20 std::cout<<t.mult()<<std::endl;
21 const Test& t2=t;
22 std::cout<<t.assign()<<std::endl;
23 std::cout<<t1.assign()<<std::endl;
24 //std::cout<<t2.assign()<<std::endl; // 为什么这行不能通过编译?
25 return 0;
26 }
 

其解决方法就是将 assign() 函数重载一份,用 const 限制其行为,然后返回一个常引用:

const int&assign()const {
        return x;
}

这样,程序就可以在 gcc 下编译通过了

相关阅读 更多 +
排行榜 更多 +
方块枪战战场安卓版

方块枪战战场安卓版

飞行射击 下载
战斗火力射击安卓版

战斗火力射击安卓版

飞行射击 下载
空中防御战安卓版

空中防御战安卓版

飞行射击 下载