C++友元函数无法访问类的公共函数
C++ friend function can't access public function of the class
这是 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
对象的常量引用。
相关文章:
- C++模板来检查友元函数的存在
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 模板类中的模板友元函数
- C++ 17 个友元函数声明和内联命名空间
- 将派生类的构造函数声明为父类的友元
- 友元函数需要一个帮助程序函数
- 在基/派生类的成员函数/友元函数中派生* 到 Base* 的转换
- 模板类的非模板函数友元