在友方功能中不能使用重载运算符

问题描述 投票:0回答:1

我有以下代码。在我的.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中,我已经将运算符<<函数声明为朋友,并声明了实际函数。但是如果我尝试在运算符<< I get“中使用它,则没有operator []匹配这些操作数”。我知道这是一个新手的错误,但我似乎无法弄明白。

c++ operator-keyword friend
1个回答
1
投票

char& String::operator[](int index)不是const函数,所以你不能在你的流媒体操作符中的const这样的str对象上调用它。你需要一个像这样的版本:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.