C ++好友函数无法访问类的公共函数[重复]

问题描述 投票:-2回答:2

这个问题在这里已有答案:

这是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;
        }
};

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

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

c++ operator-overloading friend
2个回答
3
投票

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

int size() const {
    return top;
}

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


2
投票

声明成员函数size就像一个常量成员函数

    int size() const
    {
        return top;
    }

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

© www.soinside.com 2019 - 2024. All rights reserved.