下面的代码(我只保留了相关部分)可以转换为使用静态成员函数而不是友元自由函数吗?如果不是,为什么不呢?我试图以多种不同的方式将其转换为使用静态成员函数,但失败了(针对不同的变体不断出现不同的编译器错误),但我从 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/