`

c++ - overloaded subscript operator - []

    博客分类:
  • c++
c++ 
阅读更多

You can overload the subscript operator, a typical scenario that you may use the subscriptor overload operator is when you design the String class, where you want the user to access the element at ith indext, which is a char type. 

 

However, what is the return type of the subscriptor operator ? for const object, it should return a const char reference or we simple return a char reference regardless?

 

here is the example, below is the definition of MyString class. 

 

 

/**
* file 
*  MyString.h
*  
*  this header is the demonstrate the use of user defined constructor and overload operator
*/
#include <iostream>

class MyString
{
public :
	// overload set of constructors
	// provide automatic initialization
	MyString(const char * = 0);
	MyString (const MyString & );

	// destructor: automatic deinitialization
	~MyString();

	// overload set of assignment operators
	MyString&  operator ==(const char *) const;
	MyString& operator ==(const MyString &) const;
	
	// member access function 
	int size() { return _size; } 
	char * c_str() {  return _string; } 

	const char& operator[](int elem) const;
	char & operator[] (int elem);  
	//// I love better the definition above
	//// ths is not safe..
	//char& operator[](int elem) const;

private:
	int _size;
	char * _string;
protected:
};

 

 

 

As you can see that  we providing two overloaded [] operator functions. 

 

below is the MyString implementation code. 

 

 

/**
* file 
*   MyString.cpp
*
*   this is the MyString.cpp 
*/
#include "stdafx.h"
#include "MyString.h"
#include <iostream>
#include <vector>
#include <assert.h>
#include <cstddef>
#include <utility>
#include <cassert>
#include <cstring>

using std::cout;
using std::endl;
using std::cerr;
using std::strcat;
using std::strlen;
using std::strcmp;
using std::strcpy;

/** 
MyString
*
*/
MyString::MyString(const char * name_) { 

	if (name_ != NULL) {
		_size = strlen(name_);
		_string = new char[_size + 1];
		strcpy(_string, name_);
	} else 
	{
		_string = NULL;
		_size = 0;
	}
}

MyString::MyString(const MyString& rhs) {
	// aovid the self coyping 
	if (this != &rhs) {
		_size = rhs._size;
		if (rhs._string != NULL) {
			delete _string;
			_string = new char[_size + 1];
			strcpy(_string, rhs._string);
		}
	}
}

MyString::~MyString() {
	delete _string;
}


char & MyString::operator[](int elem) {
	assert(elem >= 0 && elem < _size);
	return _string[_size];
}

const char & MyString::operator[](int elem) const { 
	assert(elem >= 0 && elem < _size);
	return _string[_size];
}


 

 

 

so that given the above declaration , you can use the [] operator as follow. 

 

 

void test_MyString() 
{
	MyString mystring;
	char ch = mystring[0];
	mystring[0] = 'b';

	const MyString & mystringRef = mystring;
	mystringRef[0] = 'a'; // error, since the conference MyString& return a const char referece, it does not allow writting..
}
 

 

the code above shows my way of designing overload subscriptor operator.

 

however, to simplify the task,  you can also design the subscriptor as follow.

 

suppose that you can change the declaration to this :

 

 

class MyString { 
  char &  operator[](int elem) const { 
  	assert(elem >= 0 && elem < _size);
  	return _string[_size];
  }
}
 
 

 

 

however, the code 

 

 

void test_MyString() 
{
	MyString mystring;
	char ch = mystring[0];
	mystring[0] = 'b';

	const MyString & mystringRef = mystring;
	mystringRef[0] = 'a'; // it works, but however,this is not the desired behavior, as you directly can modify the const object
}
分享到:
评论

相关推荐

    json error: Use of overloaded operator [] is ambiguous错误的解决方法

    今天小编就为大家分享一篇关于json error: Use of overloaded operator [] is ambiguous错误的解决方法,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

    try-catch-overloaded:该存储库包含用于重载TryCatch语句的TS和JS库

    尝试捕获超载该软件包包含重载Try / Catch语句的功能。动机添加自定义错误需要手动检查哪种类型的错误我们收到的是catch块,因为JS没有catch过载。 例如class UserNotFoundError extends Error { // ......

    一维动态数组实现的矩阵类

    鸣谢:CSDN上supermegaboy君的C/C++左值性精髓,读后略有所感,空闲时重构了下大学时的作业,着重区分了函数返回值的左右值 =================================================附录:接口函数======================...

    Rad Studio Delphi C++builder XE 10.4 Patch2

    RSP-20372 A generic "reference to function" will only match the first of several overloaded functions RSP-19714 Win32 compiler - Memory corruption with array helpers RSP-18241 *.c source files, added ...

    自定义的矩阵类,内含源码与测试工程

    鸣谢:CSDN上supermegaboy君的C/C++左值性精髓,读后略有所感,空闲时重构了下大学时的作业,着重区分了函数返回值的左右值 =================================================附录:接口函数======================...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Features ...

    WOLK - Working Overloaded Linux Kernel-开源

    WOLK是稳定的开发内核,其中包含许多项目中的许多有用补丁。 目标:稳定性,可伸缩性,性能,最重要的是:安全性。

    Exploring C++ 11

    Exploring C++ divides C++ up into bite-sized chunks that will help you learn the language one step at a time. Assuming no familiarity with C++, or any other C-based language, you’ll be taught ...

    C++ 标准 ISO 14882-2011

    1.7 The C++ memory model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1.8 The C++ object model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    Overloaded-kernel-for-XPSP3.rar_内核 重载_内核重载_重载内核

    用于XP SP3的重载内核,用WDK7.1.0编译通过。可在虚拟机,物理机使用

    kbmMemTable 7.69 for XE8

    Whats new in v. 7.69.00 May 30 2015 ...- Added new overloaded AddIndex2/AddFilteredIndex2 directly taking TkbmMemTableCompareOptions instead of TIndexOptions. - Updated demos to no longer use BDE.

    kbmMemTable_76900

    We are happy to announce the latest and ...- Added new overloaded AddIndex2/AddFilteredIndex2 directly taking TkbmMemTableCompareOptions instead of TIndexOptions. - Updated demos to no longer use BDE.

    Google C++ International Standard.pdf

    4.4 The C++ memory model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 4.5 The C++ object model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    Version 1.7 ----------- - ADD: Delphi/CBuilder 10.2 Tokyo now supported. - ADD: Delphi/CBuilder 10.1 Berlin now supported. - ADD: Delphi/CBuilder 10 Seattle now supported. - ADD: Delphi/CBuilder XE8 ...

    Zabbix动态监控磁盘I/O

    NULL 博文链接:https://20120923lina.iteye.com/blog/2258119

    Functionally Overloaded Linux Kernel-开源

    该项目旨在将尽可能多的内核项目集中在一起,在可能的情况下消除冲突,以便实验性内核项目可以更安全地获得更大的曝光度,并可以在更多不同的条件下对这些项目进行测试

    用递归的方法画分形图

    错误 1 error C2668: 'sqrt' : ambiguous call to overloaded function d:\wordplay\c++\范例\fractral递归方法画分图形\stdafx.cpp 19 错误 2 fatal error C1903: unable to recover from previous error(s); ...

    程序语言设计原理习题解答

    2.16 Combining Imperative and Object-Oriented Features: C++ 101 2.17 An Imperative-Based Object-Oriented Language: Java 104 2.18 Scripting Languages: JavaScript, PHP, and Python 108 2.19 A C-...

    Zabbix监控系统深度实践

    《Zabbix监控系统深度实践》是一本由浅入深,全面讲解Zabbix应用与原理的技术书籍,也是作者多年实战经验的总结和浓缩。在概念篇,从一个简单但完整的入门案例讲起,案例中有最基本的概念介绍,通过案例帮助那些只要...

    VC帮助文档

    In the alphabetical listing section, each class description includes a member summary by category, followed by alphabetical listings of member functions, overloaded operators, and data members. ...

Global site tag (gtag.js) - Google Analytics