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

来源:互联网 发布:png软件图标 编辑:程序博客网 时间:2024/06/05 21:13

#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;

}

原创粉丝点击