gpt4 book ai didi

c++ - 为 mystring 类重载数组运算符

转载 作者:搜寻专家 更新时间:2023-10-31 02:19:03 25 4
gpt4 key购买 nike

我需要帮助弄清楚如何为我必须创建的 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::operator [] 的正文会是什么样子?

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;

关于c++ - 为 mystring 类重载数组运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33967700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com