2013-05-04 53 views
1

下面的代码C++编译在Windows上,但错误编译的Visual Studio 2012下就好了快递,Windows 8的下OS X GCC

但在我的首选平台,Eclipse的朱诺,GCC 4.2 OS X 我收到以下错误:

../src/Test.cpp:20:错误: '的std :: istream的& TestNS ::运算符>>(的std :: istream的&,TestNS ::测试&)' 应该被宣布里面' TestNS'

#include <cstdio> 
#include <cstdlib> 
#include <iostream> 

using std::istream; 

namespace TestNS 
{ 
class Test 
{ 
    friend istream &operator>>(istream &in, Test &value); 

public: 
    Test(double real, double image); 

private: 
    double real; 
    double image; 
    void initialize(double real, double image); 

}; 
} 

#include <cstdio> 
#include <cstdlib> 
#include <iostream> 
#include "Header.h" 

using std::istream; 
using namespace TestNS; 

TestNS::Test::Test(double real = 0.0, double image = 0.0) : real(real), image(image) 
{ 

} 

void TestNS::Test::initialize(double real, double image) 
{ 
this->real = real; 
this->image = image; 
} 

istream& TestNS::operator>> (istream &in, TestNS::Test &value) 
{ 
value.real = 10.0; 
value.image = 10.0; 

return in; 

} 

int main() 
{ 

} 

任何帮助将是最有帮助的。 从事学校项目的作业。

+0

TestNS不是类,它是头文件中的名称空间,教授指出这是需要的。 – 2013-05-04 04:36:54

+0

赋值表示必须是朋友函数。 – 2013-05-04 04:37:37

+0

没有TestNS ::函数是全局函数不是朋友函数,代码编译在Windows,Visual Studio中,但不是Eclipse GCC OS X – 2013-05-04 04:42:54

回答

4

看来GCC在给出错误方面是正确的。在您的示例中,operator>>的朋友声明确实指定operator>>将成为TestNS的成员,但实际上并未在此处声明。你仍然需要内部TestNSoperator>>声明之前,你可以在外面TestNS定义它:

namespace TestNS 
{ 
    class Test 
    { 
     friend istream &operator>>(istream &in, Test &value); 

    public: 
     Test(double real, double image); 

    private: 
     double real; 
     double image; 
     void initialize(double real, double image); 

    }; 

    istream &operator>>(istream &in,Test &value); // need this 
} 

现在,这是确定的:

istream& TestNS::operator>> (istream &in, TestNS::Test &value) 
{ 
    value.real = 10.0; 
    value.image = 10.0;   
    return in;  
} 

标准的相关部分是7.3.1.2 P2(用于C++ 03):

Members of a named namespace can also be defined outside that namespace by explicit qualification of the name being defined, provided that the entity being defined was already declared in the namespace...

下一段指出(虽然有些间接),尽管类中的朋友声明确实使该函数成为名称空间的成员,但实际上并没有在那里声明它,因为函数的名称在名称空间内变得可见需要单独声明:

If a friend declaration in a non-local class first declares a class or function, the friend class or function is a member of the innermost enclosing namespace. The name of the friend function is not found by simple name lookup until a matching declaration is provided in that namespace scope (either before or after the class declaration granting friendship).

+0

谢谢Vaughn,提供了很棒的参考资料。 – 2013-05-04 07:36:12