代码之家  ›  专栏  ›  技术社区  ›  DimK

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

  •  -2
  • DimK  · 技术社区  · 8 年前

    这是C++中堆栈类实现的摘录:
    Stackdemo。水电站

    #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’参数会丢弃限定符[-fppermissive]”。显然,我一次只能使用一个循环。既然size()只返回top的值,为什么会有问题?

    2 回复  |  直到 8 年前
        1
  •  3
  •   463035818_is_not_an_ai    8 年前

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

    int size() const {
        return top;
    }
    

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

        2
  •  2
  •   Vlad from Moscow    8 年前

    声明成员函数 size 类似于常量成员函数

        int size() const
        {
            return top;
        }
    

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