不能在友元函数中使用重载运算符

Cannot use overloaded operator in friend function

本文关键字:重载 运算符 友元 函数 不能      更新时间:2023-10-16

我有以下代码。 在我的 .h 文件中:

#ifndef STRING_H
#define STRING_H
#include <cstring>
#include <iostream>
class String {
private:
char* arr; 
int length;
int capacity;
void copy(const String& other);
void del();
bool lookFor(int start, int end, char* target);
void changeCapacity(int newCap);
public:
String();
String(const char* arr);
String(const String& other);
~String();
int getLength() const;
void concat(const String& other);
void concat(const char c);
String& operator=(const String& other);
String& operator+=(const String& other);
String& operator+=(const char c);
String operator+(const String& other) const;
char& operator[](int index);
bool find(const String& target); // cant const ?? 
int findIndex(const String& target); // cant const ??
void replace(const String& target, const String& source, bool global = false); // TODO:

friend std::ostream& operator<<(std::ostream& os, const String& str);
};
std::ostream& operator<<(std::ostream& os, const String& str);
#endif

.cpp文件:

//... other code ...
char& String::operator[](int index) {
if (length > 0) {
if (index >= 0 && index < length) {
return arr[index];
}
else if (index < 0) {
index = -index;
index %= length;
return arr[length - index];
}
else if (index > length) { 
index %= length;
return arr[index];
}
}  


std::ostream & operator<<(std::ostream & os, const String & str) {
for (int i = 0; i < str.length; i++) {
os << str.arr[i]; // can't do str[i]
}
return os;
}

在 .h 中,我将运算符<<函数声明为朋友,并声明了实际函数。但是如果我尝试在运算符中使用它<<我会得到"没有运算符 [] 匹配这些操作数"。我知道这是一个菜鸟的错误,但我似乎无法弄清楚。

char& String::operator[](int index)

不是const函数,因此无法在流式处理运算符中的const对象(如str(上调用它。 您需要一个版本,例如:

const char& String::operator[](int index) const { ... }

(你可以简单地返回char,但const char&让客户端代码获取返回字符的地址,这支持例如字符之间距离的计算。