C++友元函数无法访问类的公共函数

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

本文关键字:函数 友元 C++ 访问      更新时间:2023-10-16

这是 C++ 中 Stack 类实现的摘录:
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;
        }
};

在这里,我使用一个简单的驱动程序来测试它:
堆栈测试.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;
}

我的问题是在运算符重载函数中:第一个循环工作并产生预期的输出,但第二个循环不起作用,并给出错误"传递'const Stack'作为'this'参数丢弃限定符[-permissive]"。显然,我一次只使用一个循环。为什么会出现问题,因为 size(( 只返回 top 的值?

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

int size() const {
    return top;
}

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

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

    int size() const
    {
        return top;
    }

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