`

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错误的解决方法

    然而,当使用C++的`Json::Value`库(如JsonCpp)时,可能会遇到“Use of overloaded operator [] is ambiguous”这样的编译错误。这个错误通常发生在尝试使用0作为数组下标访问`Json::Value`对象时。 在C++中,`[]`...

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

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

    C++ 标准 ISO 14882-2011

    可重载声明(Overloadable declarations)、声明匹配(Declaration matching)、重载解析(Overload resolution)、重载函数的地址(Address of overloaded function)、重载运算符(Overloaded operators)、内建...

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

    鸣谢: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 ...

    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 ...

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

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

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

    在Windows XP Service Pack 3(XP SP3)环境中,"Overloaded-kernel-for-XPSP3.rar" 提供了一个经过重载的内核,这表明它可能包含了对原始XP内核的修改或扩展,以实现特定的目标。这种内核通常由开发人员使用Windows...

    C++常用函数查询器

    - **重载函数(Overloaded Functions)**:C++允许函数名相同但参数列表不同的函数存在,这就是重载。通过这种方法,一个函数可以根据传入的不同参数类型执行不同的操作。 - **模板函数(Template Functions)**:...

    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++函数详解

    5. **重载函数(Overloaded Functions)**:C++允许在同一作用域内用相同的名字定义多个函数,只要它们的参数列表不同即可。这是实现方法多态性的一种方式。 6. **默认参数(Default Arguments)**:在定义函数时...

    C++ Primer Plus 第五版源程序

    在源码中,你会看到函数的定义、声明和调用,以及函数模板(function template)和重载函数(overloaded functions)的应用。 C++还支持动态内存管理,通过new和delete操作符分配和释放内存。在源码中,你会看到...

    c++ Strings

    The `std::string` class in the C++ Standard Library addresses these limitations by providing a true string type that supports common operations through both member functions and overloaded operators....

    c++实现任意维数向量类的操作

    5. **算术运算符重载(Overloaded Arithmetic Operators)**:为了方便向量之间的加法、减法、乘法(标量与向量的乘法,向量的点积和叉积等)操作,我们需要重载一些算术运算符,如`+`, `-`, `*`等。 6. **友元函数...

    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.

    C++辅助练习题

    1. **重载函数(Overloaded Functions)**: - 在实验1.11中,`Max`函数被重载以处理不同类型的数值(整数、长整型、单精度浮点数和双精度浮点数)。函数重载允许我们使用相同的函数名但提供不同的参数列表,从而根据...

    C++常见错误及解决方案

    **错误信息**: `error C2676: binary ‘&gt;&gt;’: ‘class std::basic_ostream, struct std::char_traits&lt;char&gt;&gt;’ does not define this operator or a conversion to a type acceptable to the predefined operator` ...

    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.

Global site tag (gtag.js) - Google Analytics