c++ - 好友方法错误

标签 c++

我收到此错误消息:

'friend' used outside of class.

我的标题有这一行

private:
        friend ostream& operator << (ostream&, card&);

cpp 文件中是

friend ostream& operator << (ostream& outStream, card& card)
{
    Suit suit=card.getSuit();
    Rank rank=card.getRank();
    string str;
    switch(rank)
        { /*...*/ }
    outStream<<str;
    return outStream;

像这样。

我进行了搜索,但大多数情况下它说我需要没有 friend 的同一个类(class),但我试过了,但没有成功。你能给我一些建议吗?

谢谢

最佳答案

删除 .cpp 文件中的 friend。它仅在头文件中的 class 定义中是必需的(并且允许的)。

在头文件中,你声明运算符是你的 friend :

private:
    friend ostream& operator << (ostream&, card&);

这是类的属性。

在源文件中,只需“正常”定义运算符:

ostream& operator << (ostream& outStream, card& card)
{
    // ...
}

在这里,friend 没有意义:谁的 friend ?多个类可能会将运算符声明为友元。

关于c++ - 好友方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23166911/

相关文章:

c++ - 移走由 std::shared_ptr 管理的对象是否有效

c++ - 从二进制索引树中删除元素

c++ - OpenSceneGraph 未加载 openflight 插件

c++ - constexpr 定义声明为 const 的文字类型的静态数据成员

c++ - cplexmiqp MATLAB 的 CPLEX 等效 C++

c++ - c++ vector 构造函数的奇怪行为

C++ getInt() 函数(附​​有 java 等价物)

c++ - OpenGL For 循环(随机月亮生成)

c++ - CAtlRegExp 格式的正则表达式不起作用?

c++ - 注册表设计