首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

重载函数const 有关问题

2012-04-08 
重载函数const 问题重载(),使得a(1,1)表示数组的一个元素a[1][1]一个返回 int & 另一个返回 const int&声

重载函数const 问题
重载(),使得a(1,1)表示数组的一个元素a[1][1] 
一个返回 int & 另一个返回 const int&
声明:
int &operator()(int,int);
const int &operator()(int,int)const;
这样的 如果我声明一个对象b
那么当我这样使用时 b.a(1,1)时 它是调用哪个函数?

[解决办法]
如果要模拟a[1][1]这种操作,需要使用一个中间类来满足。

C/C++ code
#include <iostream>#include <vector>using namespace std;class A{protected:    int data[10];public:    int operator [] (int i)    {        if (i < 0 || i > 9) // 越界判断        {            return data[0]; //抛出异常或者……        }        return data[i];    }};class B{protected:    A data[10]; // 只是举个例子,为了简单直接使用10public:    A& operator [] (int i)    {        if (i < 0 || i > 9) // 越界判断        {            return data[0]; //抛出异常或者……        }        return data[i];    }};int main(int argc, char* argv[]){    B b;    cout << b[1][2] << endl;  //事实上输出的值是没初始化的,仅仅表示能通过编译而已    system("pause");    return 0;}
[解决办法]
b.a(1,1)
根据你的b对象是否有const修饰符来决定调用的函数类型,如果有那么调用const成员版本,否则调用非const成员版本

热点排行