c++ - 这可以在不使用 friend 的情况下完成吗?

标签 c++ friend-function member-functions

下面的代码(我只保留了相关部分)可以转换为使用静态成员函数而不是友元自由函数吗?如果不是,为什么不呢?我试图以多种不同的方式将其转换为使用静态成员函数,但失败了(针对不同的变体不断出现不同的编译器错误),但我从 this question 的答案中收集到了你可以使用任何一个来做同样的事情。由于 C++ 语法的某些属性,这在技术上不是真的吗?我哪里出错了?

class Tape {
    public:
        friend std::ostream &operator<<(std::ostream &, Tape &);

    private:
        char blank;
        size_t head;
        std::string tape;
}


std::ostream &operator<<(std::ostream &out, Tape &tape) {
    out << tape.tape << std::endl;
    for (size_t i = 0; i < tape.head; i++)
        out << ' ';
    out << '^' << std::endl;
    return out;
}

最佳答案

根据C++标准

6 An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

所以你可能没有定义operator <<作为类的静态成员函数。 然而,在运算符的定义中,您可以使用静态成员函数。 例如

#include <iostream>

class A
{
private:
    int x = 10;
public:
    static std::ostream & out( std::ostream &os, const A &a )
    {
        return ( os << a.x );
    }
};

std::ostream & operator <<( std::ostream &os, const A &a )
{
    return ( A::out( os, a ) );
}

int main() 
{
    A a;
    std::cout << a << std::endl;

    return 0;
}

与 C++ 相反,C# 运算符函数被定义为静态的。:)

关于c++ - 这可以在不使用 friend 的情况下完成吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23142126/

相关文章:

C++程序控制终端窗口

c++ - 指向独立函数和 friend 函数的指针之间的区别

c++ - 使用 CRTP 访问派生类的 protected 成员

c++ - 如何使用指向成员函数的指针进行切换?

c++ - 为什么这个返回类型有效?

c++ - 内联汇编或单独的汇编文件

c++ - Pimpl 习语和交换

c++ - 如何修复以前工作的注入(inject)模板友元函数?

c++ - 对成员函数使用 std::function

c++ - 有没有办法创建一个以成员函数或成员作为参数的函数?