lundi 2 juillet 2018

Why I get error while I try to reed private fields from a friend function?

given the following code:

template<class T>
class A {
    T* arr;
    int size;
public: 
    explicit A(int size); 

    template<class S>
    friend ostream& operator<<(ostream& os, const A& a);
};


template<class T>
A<T>::A(int size) :
        arr(new T[size]), size(size) {
    for (int i = 0; i < size; i++) {
        arr[i] = T();
    }
}


template<class T>
ostream& operator<<(ostream& os, const A<T>& a) {
    for (int i = 0; i < a.size; i++) {
        os << a.arr[i] << " "; // error
    }
    return os;
}

int main() {
    A<int> a(5);
    std::cout << a << std::endl;
}

I get the following error:

'int A::arr' is private
'int* A::size' is private

But I don't understand. operator<< is defined as friend, hence, it's need to be with access to the fields that defined in class A (any to the private fields) , so what I still get error?

Aucun commentaire:

Enregistrer un commentaire