g ++ 4.5找不到朋友函数 [英] g++ 4.5 can't find a friend function
问题描述
G'day!
我有一个关于在C ++中使用 friend
的问题。考虑下面的代码:
#include< ostream>
struct F {
};
struct N {
friend std :: ostream&运算符<< (std :: ostream& const N&);
friend std :: ostream&运算符<< (std :: ostream& const; F& amp;);
};
void foo(std :: ostream& out){
F bar;
out<<酒吧;
}
我的理解总是: friend
类似于具有附加属性的 static
, friend
函数可以访问类。在这种假设下,代码应该编译,因为有一个运算符<
需要一个 ostream&
(const) F&
。
看来g ++ 4.0分享我的想法,因为它接受那个代码。然而,更新的g ++ 4.5(.2)拒绝带有消息的代码:
ns.cc: foo(std :: ostream&)':
ns.cc:14:10:error:没有匹配的'operator<<'in'out< bar'
是g ++ 4.5错误或是我(和g ++ 4.0)错了吗?
(将朋友声明移动到 F
类的解决方案没有帮助,因为 <
需要访问 N
的私有部分。)
<
Stefan
您还必须声明结构外的运算符。 gcc 4.4报告了相同的错误。
#include< ostream>
struct F {
};
struct N {
friend std :: ostream&运算符<< (std :: ostream& const N&);
friend std :: ostream&运算符<< (std :: ostream& const; F& amp;);
};
std :: ostream&运算符<< (std :: ostream& const N&);
std :: ostream&运算符<< (std :: ostream& const; F& amp;);
void foo(std :: ostream& out){
F bar;
out<<酒吧;
}
G'day!
I have a question around the use of friend
in C++. Consider the following piece of code:
#include <ostream>
struct F {
};
struct N {
friend std::ostream& operator<< (std::ostream&, const N&);
friend std::ostream& operator<< (std::ostream&, const F&);
};
void foo(std::ostream &out) {
F bar;
out << bar;
}
My understanding always was, that friend
is similar to static
with the additional property that the friend
function has access to the private part of the class. Under that assumption, the code should compile, since there is an operator<<
that takes an ostream&
and a (const) F&
.
It appears that g++ 4.0 shares my thoughts on this, as it accepts that code. The much newer g++ 4.5(.2) however, rejects the code with the message:
ns.cc: In function 'void foo(std::ostream&)':
ns.cc:14:10: error: no match for 'operator<<' in 'out << bar'
is g++ 4.5 wrong or am I (and g++ 4.0) wrong?
(The solution to move the friend declaration into the F
class doesn't help, as the operator<<
will need access to the private part of N
.)
Regards, Stefan
You have to declare the operators outside the struct as well. Same error is reported by gcc 4.4.
#include <ostream>
struct F {
};
struct N {
friend std::ostream& operator<< (std::ostream&, const N&);
friend std::ostream& operator<< (std::ostream&, const F&);
};
std::ostream& operator<< (std::ostream&, const N&);
std::ostream& operator<< (std::ostream&, const F&);
void foo(std::ostream &out) {
F bar;
out << bar;
}
这篇关于g ++ 4.5找不到朋友函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!