这可以在不使用朋友的情况下完成吗
Can this be done without using friends?
以下代码(我只保留了相关部分)是否可以转换为使用静态成员函数而不是无友函数?如果没有,为什么不呢?我试图以多种不同的方式将其转换为使用静态成员函数,但都失败了(针对不同的变体,不断出现不同的编译器错误),但我从这个问题的答案中了解到,你可以使用其中任何一种来做同样的事情。由于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操作员功能应为非静态成员功能,或是非成员函数,并且至少有一个参数的类型为类、对类的引用、枚举或对枚举。
因此,您可能不会将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++相反,运算符函数被定义为静态。:)
由于std::ostream
参数是运算符的左手边,因此它不能是类的成员(静态或其他)。
因此,它必须是一个免费函数,因为您不能向std::ostream
添加成员。
不过,它不必是的朋友,而是可以调用公共成员
我个人更喜欢这种方法,因为它不会把任何东西暴露在外面。
class Tape {
public:
void print(std::ostream &out) const
{
out << tape << std::endl;
for (size_t i = 0; i < head; i++)
out << ' ';
out << '^' << std::endl;
}
};
std::ostream& operator<<(std::ostream &out, const Tape &tape)
{
tape.print(out);
return out;
}
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 为什么在某些情况下不写入此文件?
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 在这种情况下,我们可以使用静态而不是朋友吗,还有其他解决方案是什么
- C 交叉相关单例.在没有朋友的情况下,我如何使用彼此的功能
- 如何在没有包含朋友的情况下使用过载操作员
- 在没有朋友的情况下向私有构造函数授予访问权限
- 在没有朋友的情况下测试C++中的私有类成员
- 在没有朋友的情况下为基类提供受保护的访问权限
- 在没有朋友c++的情况下访问其他类的私有数据
- 这可以在不使用朋友的情况下完成吗