我正在尝试使用g ++编译以下代码(从实际使用中简化):
namespace A {
class B;
}
A::B operator+(A::B a, A::B b);
namespace A {
class B {
private:
int i;
public:
B() : i(0) {}
B(int j) : i(j) {}
friend B ::operator+(B a, B b);
};
}
A::B operator+(A::B a, A::B b) {
return A::B(a.i + b.i);
}
int main() {
A::B a(1), b(2);
A::B c = a+b;
return 0;
}
据我所知,B类中的friend声明是正确的,并且需要:: global scope声明,否则编译器会假定A :: operator +(B a,B b)。
但是,在编译时,gcc会给出错误消息
ISO C++ forbids declaration of ‘operator+’ with no type
我不知道如何解决这个问题。之后的错误消息给人的印象是gcc忽略了该行中B和::之间的空格,而是把它解释为B的成员函数的朋友声明。我怎么能告诉它我想要什么?
答案 0 :(得分:1)
以下列方式在类定义中声明friend运算符
friend B (::operator+) (B a, B b);
或喜欢
friend B (::operator+(B a, B b));
否则编译器认为它就像声明的类的成员函数而没有显式的返回类型(int暗示)
friend B::operator+(B a, B b);
虽然将它声明为
会好得多friend B (::operator +)( const B &a, const B &b);
答案 1 :(得分:1)
::
被视为应用于B
的范围解析运算符:friend B::operator+(B a, B b);
为了使其正常工作,您应该在返回的类型名称后添加friend
关键字:
B friend ::operator+(B a, B b);