C++ 无法在友元函数中使用重载运算符
我有以下代码。 在my.h文件中:C++ 无法在友元函数中使用重载运算符,c++,operator-keyword,friend,C++,Operator Keyword,Friend,我有以下代码。 在my.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 lookFo
#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不是常量函数,因此不能在流式操作符中的常量对象(如str)上调用它。您需要的版本如下:
const char& String::operator[](int index) const { ... }
您可以简单地返回char,但const char&让客户端代码获取返回字符的地址,例如,它支持计算字符之间的距离。@nivalen292:这可能还允许您将缺少的const添加到find方法中。