gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 17:39:45 25 4
gpt4 key购买 nike

我在命名空间 my_namespace 中为类 my_type 声明了运算符。

namespace my_namespace {
class my_type
{
friend std::ostream& operator << (std::ostream& out, my_type t);
}
}

我试图在实现文件中定义这些运算符,但是当我写这样的东西时

std::ostream& my_namespace::operator << (std::ostream& out, my_type t)
{
out << t;
return out;
}

我收到错误信息

错误:...运算符应该在“my_namespace”中声明

当我把它改成

namespace my_namespace {
std::ostream& operator << (std::ostream& out, my_type t)
{
out << t;
return out;
}
}

然后它编译了,但我不明白这个问题。为什么编译失败?一切都对吗?我希望能链接到标准,因为我真的不知道要搜索什么。

已添加

文件.h

#ifndef A_H
#define A_H

#include <iosfwd>

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

#endif

文件.cpp

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

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

int main() {}

这里是完整的例子。这在 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);
}

我一直在想,就可见性而言,在类里面声明友元运算符与在类外声明是一样的……看起来不是。谢谢。

提前致谢。

最佳答案

The error message says it all, actually. You can keep your function definition in the implementation file, but you need to declare it in the namespace first:

namespace my_namespace {
std::ostream& operator << (std::ostream& out, my_type t);
}

C++ 标准对此非常清楚:

7.3.1.2/3:

Every name first declared in a namespace is a member of that 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 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). If a friend function is called, its name may be found by the name lookup that considers functions from namespaces and classes associated with the types of the function arguments (3.4.2). When looking for a prior declaration of a class or a function declared as a friend, and when the name of the friend class or function is neither a qualified name nor a template-id, scopes outside the innermost enclosing namespace scope are not considered. .

以下链接更简单,并添加了几个示例:http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr043.htm

所以我会说 gcc 在这里是错误的。 。相关句子似乎是“直到在该命名空间范围内提供匹配声明(在授予友元的类声明之前或之后)之前,通过简单的名称查找找不到 friend 的名字。”。 p>

关于c++ - gcc 无法编译带有前缀命名空间的运算符定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4757871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com