[英]Cannot use overloaded operator in friend function
我有以下代碼。 在我的.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;
}
在.hi中,將operator <<函數聲明為朋友,並聲明了實際函數。 但是,如果我嘗試在operator <<中使用它,則會得到“沒有operator []與這些操作數匹配”。 我知道這是一個菜鳥錯誤,但我似乎無法弄清楚。
char& String::operator[](int index)
不是const
函數,因此您不能在流運算符中的const
對象(如str
上調用它。 您需要一個類似的版本:
const char& String::operator[](int index) const { ... }
(您可以簡單地返回char
,但是const char&
可以讓客戶端代碼獲取返回字符的地址,該地址支持例如字符之間的距離的計算。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.