c++初学者

专注技术开发

const函数重载

#include <stdlib.h> #include <iostream>
using namespace std;

class tgh
{
public:
    tgh():i(
3){}
   
const int a() const {return 5;}
   
int a(){return i;}
protected:
   
int i;
private:
};

void main()
{
   
const tgh v;
    tgh s;
   
const int i=s.a();//调用的是int a()
   
int const j=s.a();//调用的是int a()
    printf(
"%d,%d",j,i);
   
const int k = v.a();();//调用的是const int a() 
    cout
<<k<<endl;
    system(
"pause");
}

结果是3,35

posted on 2008-04-15 10:23 大海 阅读(2343) 评论(4)  编辑 收藏 引用

评论

# re: const函数重载 2008-04-15 12:44 ycc

与返回值是const int, int const都没有关系~  回复  更多评论   

# re: const函数重载 2008-04-15 19:31 啸天猪

函数重载机制中是不考虑函数返回值这个因素的

你这个例子里的重载是根据成员函数的隐式参数this指针的类型来进行的  回复  更多评论   

# re: const函数重载 2008-04-15 19:48 ss

const int k = v.a();();//调用的是const int a()
应该是const int a() const
c++ 重载是可以根据函数的参数和函数本身的修饰符来区分,也就是说int a()const 和int a()是不同的,当然这个只能在类中使用。  回复  更多评论   

# re: const函数重载 2008-04-17 15:49 ..

内建类型返回const根本没必要.......具体参见Thinking in c++  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理