不能在友元函数中使用重载运算符
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;
}
在 .h 中,我将运算符<<函数声明为朋友,并声明了实际函数。但是如果我尝试在运算符中使用它<<我会得到"没有运算符 [] 匹配这些操作数"。我知道这是一个菜鸟的错误,但我似乎无法弄清楚。
char& String::operator[](int index)
不是const
函数,因此无法在流式处理运算符中的const
对象(如str
(上调用它。 您需要一个版本,例如:
const char& String::operator[](int index) const { ... }
(你可以简单地返回char
,但const char&
让客户端代码获取返回字符的地址,这支持例如字符之间距离的计算。
相关文章:
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 在 myVector 类中重载运算符 + 时出错
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 如何在 cpp 中重载运算符 +=?
- C++ 如何重载 [] 运算符并进行函数调用
- 重载运算符的范围是什么?它是否会影响作为类成员的集合的插入函数?
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 重载运算符有地址吗?
- 如何迭代重载运算符 [] 的类?
- 重载运算符与添加问题
- 模板基类中的重载运算符
- 如何调用用于重载运算符"<<"的 friend 函数?
- 在 C++17 中的命名空间和子命名空间中重载运算符是不明确的
- 重载运算符<<采用谷歌 C++ 风格
- C++ 如何正确重载 + 运算符
- cout (<<) 重载运算符不打印减去的矩阵
- 如何在 c++ 中重载运算符 + 以便能够 whrite c_str = "smth" + c_str;
- 重载运算符*以获取对另一个类的实例的引用