nivalen292
nivalen292

Reputation: 73

Cannot use overloaded operator in friend function

I have the following code. In my .h file:

#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 file:

//... 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;
}

In the .h i have declared the operator<< function as a friend and made the declaration of the actual function. But if I try to use it in operator<< I get "no operator[] matches these operands". I know it is a rookie mistake but I cannot seem to figure it out.

Upvotes: 0

Views: 47

Answers (1)

Tony Delroy
Tony Delroy

Reputation: 106096

char& String::operator[](int index) is not a const function, so you can't call it on a const object such as str in your streaming operator. You'll need a version like:

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

(You could simply return char, but const char& lets client code take the address of the returned character, which supports e.g. calculations of distance between characters.)

Upvotes: 1

Related Questions