您的位置:首页 > 编程语言 > C语言/C++

《Effective C++》条款03:两个成员函数如果只是常量性不同可以被重载

2012-04-27 13:54 351 查看
#include "stdafx.h"

#include <iostream>

#include <string>

using namespace std;

class TextBlock

{

public:

TextBlock(): text(""){}

TextBlock(const char t[]): text(t){}

TextBlock(const TextBlock& tb): text(tb.text)

{

}

~TextBlock(){}const char& operator[](std::size_t position) const

{

return text[position];

}

char& operator[](std::size_t position){return text[position];}

private:

std::string text;

};

int main(int argc, char* argv[])

{

TextBlock tb("Hello");

std::cout << tb[0]; //call non-const TextBlock::operator[]

const TextBlock ctb("World");

std::cout << ctb[0] << endl; //call const TextBlock::operator[]

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐