《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;
}
#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;
}
相关文章推荐
- 创建一个CPoint类,代表平面直角坐标系中的点,创建构造函数和运算符重载函数, 运算符重载为类重载(非友元重载),可以实现计算两个点之间的距离。可以根据需要 加入自己的成员变量或成员函数
- [Effective C++]条款30: 避免这样的成员函数:其返回值是指向成员的非const指针或引用,但成员的访问级比这个函数要低
- “用成员函数重载‘+’,连接两个字符串”,这次又犯了什么错误?
- Effective C++ -----条款45:运用成员函数模板接受所有兼容类型
- Effective C++:条款45:运用成员函数模板接受所有兼容类型
- Effective c++ 条款19: 分清成员函数,非成员函数和友元函数
- effective C++ 条款 45:运用成员函数模板接受所有兼容类型
- 在c++中,静态数据成员可以被非静态成员函数调用吗?如果可以调用的话那为什么还要定义静态成员函数呢
- effective C++ 条款06如果你不想让编译器为你生成函数就应该明确拒绝
- 在类中const成员函数和非const成员函数可以作为重载成员函数同时存在
- “回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。花花非常喜欢这种拥有对称美的回文串,生日的时候她得到两个礼物分别是字符串A和字符串B。现在她非常好奇有没有办法将字符串B插入字符串A使产生的字符串是一个回文串。你接受花花的请求,帮助她寻找有多少种插入办法可以使新串是一个回文串。如果字符串B插入的位置不同就考虑为不一样的办法。
- Effective C++ 条款45 运用成员函数模板接受所有兼容类型
- C++小知识:const成员函数与非const成员函数可以重载
- 同一个类的不同对象,对象的成员函数可以互相访问各自对象的私有变量和私有成员函数
- Effective C++ -----条款35:考虑virtual函数以外的其他选择
- iOS 时间状态栏的隐藏和显示 重载两个函数即可
- 父类的正常成员函数子类可以使用,并不是继承下来 的,子类是怎么调用父类的函数 : 可能是利用了一种叫函数名联编的方法.没有隐藏的情况下用函数名字来决定调用的函数.
- C++ 类成员函数的重载(overload),重写/覆盖(override),隐藏
- 编写函数模拟掷骰子的游戏(两个骰子)。第一次掷的时候,如果点数之和为7或11则获胜;如果点数之和为2、3或12则落败;其他情况下的点数之和称为“目标”,游戏继续。在后续的投掷中,如果玩家再次掷出“目标
- C++成员函数—C++成员函数的定义和重载