Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ gcc无法编译带有前缀命名空间的运算符定义_C++_Gcc_Namespaces_Operator Overloading - Fatal编程技术网

C++ gcc无法编译带有前缀命名空间的运算符定义

C++ gcc无法编译带有前缀命名空间的运算符定义,c++,gcc,namespaces,operator-overloading,C++,Gcc,Namespaces,Operator Overloading,我在名称空间myu名称空间中声明了类myu类型的运算符 namespace my_namespace { class my_type { friend std::ostream& operator << (std::ostream& out, my_type t); } } 那就是编译,但我不明白问题所在。为什么编译失败?这一切都对吗? 我希望链接到标准,因为我真的不知道搜索什么 已添加 file.h #ifndef A_H #define A_H #i

我在名称空间
myu名称空间
中声明了类
myu类型
的运算符

namespace my_namespace {
 class my_type
 {
  friend std::ostream& operator << (std::ostream& out, my_type t);
 }
}
那就是编译,但我不明白问题所在。为什么编译失败?这一切都对吗? 我希望链接到标准,因为我真的不知道搜索什么

已添加

file.h

#ifndef A_H
#define A_H

#include <iosfwd>

namespace N
{
 class A
 {
  friend std::ostream& operator << (std::ostream& out, A& obj);
 };
}

#endif
这是一个完整的例子。这在VS2010上运行良好,但在gcc 4.4.5中给出了上述错误

已添加

嗯……是的,这个很管用

namespace N
{
    class A
    {
        friend std::ostream& operator << (std::ostream& out, A& obj);
    };
    std::ostream& operator << (std::ostream& out, A& obj);
}
名称空间N
{
甲级
{
friend std::ostream和操作员
错误消息实际上说明了一切。您可以将函数定义保留在实现文件中,但需要首先在命名空间中声明:

名称空间我的名称空间{

std::ostream&operator声明引用一组其他名称,并引入一个新名称;此新名称不能使用名称空间标识符限定,而是声明需要位于应声明新名称的名称空间块内


同样的规则也适用于定义,因为它们意味着一个声明。友元声明是特殊的,因为它位于另一个定义中,并不真正声明任何内容。

它已经在名称空间(在头文件中)中声明了,不是吗?否:“首先在友元声明中引入的友元函数或类的名称不在授予友元的类的作用域中。首先在友元声明中引入的函数的名称在包含封闭类的第一个非类作用域的作用域中。”()…这意味着您是对的…只是一个问题:您确实在源文件中包含了头文件,对吗?在关闭
之后有一个
类声明的;
?是的。我将在问题中添加更多细节。链接已失效。在GCC中,使用选项
-ffriend injection
编译此链接将成功。
#ifndef A_H
#define A_H

#include <iosfwd>

namespace N
{
 class A
 {
  friend std::ostream& operator << (std::ostream& out, A& obj);
 };
}

#endif
#include "file.h"
#include <iostream>

std::ostream& N::operator << (std::ostream& out, N::A& obj)
{
 return out;
}

int main() {}
namespace N
{
    class A
    {
        friend std::ostream& operator << (std::ostream& out, A& obj);
    };
    std::ostream& operator << (std::ostream& out, A& obj);
}
namespace my_namespace {
    std::ostream& operator << (std::ostream& out, my_type t);
}