[英]overload array operator for mystring class
因此,我需要帮助弄清楚如何为我必须创建的 mystring 类重载数组运算符。 我已经想通了其他一切,但由于某种原因数组给我带来了麻烦这是我的头文件
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
#include <cstring> // For string library functions
#include <cstdlib> // For exit() function
using namespace std;
// MyString class: An abstract data type for handling strings
class MyString
{
private:
char *str;
int len;
public:
// Default constructor.
MyString()
{
str = 0;
len = 0;
}
// Convert and copy constructors.
MyString(char *);
MyString(MyString &);
// Destructor.
~MyString()
{
if (len != 0)
delete [] str;
str = 0;
len = 0;
}
// Various member functions and operators.
int length() { return len; }
char *getValue() { return str; };
MyString operator+=(MyString &);
MyString operator+=(const char *);
MyString operator=(MyString &);
MyString operator=(const char *);
bool operator==(MyString &);
bool operator==(const char *);
bool operator!=(MyString &);
bool operator!=(const char *);
bool operator>(MyString &);
bool operator>(const char *);
bool operator<(MyString &);
bool operator<(const char *);
bool operator>=(MyString &);
bool operator>=(const char*);
bool operator<=(MyString &);
bool operator<=(const char *);
MyString operator [](MyString *);
// Overload insertion and extraction operators.
friend ostream &operator<<(ostream &, MyString &);
friend istream &operator>>(istream &, MyString &);
};
#endif
MyString 运算符 [] 的主体会是什么样子?
MyString MyString::operator [](MyString *)
{
... what goes here
}
将数组运算符与给定类的对象一起使用的语法是:
MyString s("Test");
char c = s[0];
该函数的参数是一个整数值。
因此,运算符需要声明为:
// The non-const version allows you to change the
// content using the array operator.
char& operator [](size_t index);
// The nconst version allows you to just get the
// content using the array operator.
char operator [](size_t index) const;
这不是您通常使用订阅运算符的方式
MyString MyString::operator [](MyString *)
当您使用[]
运算符时,您有什么期望? 顺便说一下,您使用的是字符串指针作为参数并接收字符串作为返回值。
通常你传递一个索引类型(通常是一个无符号整数)并返回该位置的字符。 如果这就是您想要的,您应该按照以下方式做一些事情:
你会想要这样的东西:
char& MyString::operator [](size_t position)
{
// some error handling
return str[position];
}
char MyString::operator [](size_t position) const { /* ... */ }
有关重载运算符的总体指南,请查看此问题。
我还要指出你的析构函数有点奇怪:
if (len != 0)
delete [] str;
str = 0;
len = 0;
您的缩进级别表明您希望在if
语句中发生所有事情,但只有第一个会发生。 在这种情况下,这并不是特别危险,因为只有delete
就足够了。
delete
一个空指针没有问题,并且str
和len
将在不久之后被销毁,因此您不必费心重置它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.