Нельзя использовать перегруженный оператор в функции друга - PullRequest
0 голосов
/ 06 мая 2018

У меня есть следующий код. В моем .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 я объявил функцию operator << как друга и сделал объявление фактической функции. Но если я попытаюсь использовать его в operator <<, я получу «no operator [] не совпадает с этими операндами». Я знаю, что это ошибка новичка, но я не могу понять это. </p>

1 Ответ

0 голосов
/ 06 мая 2018

char& String::operator[](int index) не является функцией const, поэтому вы не можете вызвать ее для объекта const, такого как str, в вашем операторе потоковой передачи. Вам понадобится версия вроде:

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

(Вы можете просто вернуть char, но const char& позволяет клиентскому коду брать адрес возвращаемого символа, что поддерживает, например, вычисление расстояния между символами.)

...