[英]Type conversion in ostream& operator <<
我有一个类entry
和一个ostream& operator <<
对此进行了覆盖。 我也有一个辅助类cursor
和一个类型转换operator entry()
。 然后,在我的main()
函数中,我具有以下表达式:
cout << data[4];
其中data[4]
是cursor
,但是编译失败,并显示
错误:对二进制表达式无效的操作数
我想要的是让编译器将data[4]
转换为entry
并使用其<<
操作符。 有什么方法可以以前述方式调用此ostream运算符,而不必向entry
添加特殊方法?
这是一些代码:
class entry
{
friend class cursor;
/*here comes some data*/
public:
friend ostream& operator << (ostream& out, const entry& a);
};
class cursor
{
database* data_;
size_t ind_;
friend class entry;
friend class database;
public:
cursor (database* a, size_t ind);
cursor (const cursor& a);
void operator= (const entry x);
void operator= (const cursor a);
operator entry(); //type conversion
};
这是我在main()中使用的:
cout << data[4];
当你写:
class entry
{
// ...
friend ostream& operator << (ostream& out, const entry& a);
};
尽管这在封闭范围内声明了operator<<
,但名称查找规则指出,该范围内的名称查找实际上并未找到该功能! (因为它仅是通过friend
声明的)。
如果仅通过friend
声明了一个函数,则找到该函数的唯一方法是依赖于参数的查找。 有关查找规则的详细说明,请参见此线程 。
该函数可以通过以下方式找到:
entry e;
cout << e;
因为ADL看到有一个类型为entry
的参数,所以它搜索与entry
关联的函数(包括在那里声明的朋友)。
但是, cursor c; cout << c;
cursor c; cout << c;
在搜索列表中不包括entry
(即使存在从cursor
到entry
的转换)。
要解决此问题,您需要提供运算符的非好友声明,该声明在main
处可见。 例如:
ostream& operator << (ostream& out, const class entry& a);
class entry
{
// ...
friend ostream& operator << (ostream& out, const entry& a);
};
NB。 我选择将声明放在类之前而不是之后,因为这也是解决模板朋友问题的最佳方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.