C++ 友元函数无法访问 class 的 public 函数

C++ friend function can't access public function of the class

这是 C++ 中堆栈 class 实现的摘录:
Stackdemo.hpp

#include<iostream>

using namespace std;

template<typename T>
class Stack
{
    private:
        int top;
        T *arr;

    public:
        Stack(int size)
        {
            arr = new T[size];
            top = 0;
        }

        void push(const T &x)
        {
            arr[top++] = x;
        }

        int size()
        {
            return top;
        }

        friend ostream& operator<<(ostream &out, const Stack &s)
        {
            for(int i = 0; i < s.top; ++i) out<<s.arr[i]<<' '; // Works
            for(int i = 0; i < s.size(); ++i) out<<s.arr[i]<<' '; // Doesn't work

            return out;
        }
};

这里我用一个简单的驱动程序来测试一下:
StackTest.cpp

#include<iostream>
#include"Stackdemo.hpp"

int main()
{
    Stack<int> S(5);

    S.push(1);
    S.push(2);
    S.push(3);

    cout<<S<<'\n';

    return 0;
}

我的问题出在运算符重载函数中:第一个循环工作并产生预期的输出,但第二个循环不工作并给出错误 "passing 'const Stack' as 'this' argument discards qualifiers [-fpermissive]"。显然,我一次只使用一个循环。为什么会出现问题,因为 size() 只是 returns top?

的值

您的 size() 是 non-const,因此您不能在 const Stack &s 上调用它。由于该方法实际上不修改任何成员,因此无论如何都应将其声明为 const :

int size() const {
    return top;
}

根据经验,您可以将每个成员方法声明为 const,并且仅当它需要修改成员时才删除 const.

像常量成员函数一样声明成员函数size

    int size() const
    {
        return top;
    }

因为在operator <<中使用了对类型Stack对象的常量引用。