【问题标题】:Why am I getting error "reference to struct_tag is ambiguous" with using namespace std? [duplicate]为什么使用命名空间 std 时出现错误“对 struct_tag 的引用不明确”? [复制]
【发布时间】:2016-03-19 10:12:46
【问题描述】:

我试图编写一个返回类型为 struct 变量的函数。 如果我使用 using namespace std; 会出现错误,但如果改为使用 std::,程序运行良好。

错误代码:

#include<iostream>
using namespace std;

struct distance
{
    int feet;
    int inches;
};
distance foo(distance, distance);
int main()
{
    distance d1, d2;
    cout << "Input feet of d1: ";     cin >> d1.feet;
    cout << "\nInput inches of d1: "; cin >> d1.inches;
    cout << "\nInput feet of d2: ";   cin >> d2.feet;
    cout << "\nInput inches of d2: "; cin >> d2.inches;
    distance large = foo(d1, d2);
    cout << "The larger distance is: " << large.feet << "\'-" << large.inches << "\"";
}
distance foo(distance d1, distance d2)
{
    float temp1 = d1.feet + d1.inches/12;
    float temp2 = d2.feet + d2.inches/12;
    if(temp1>temp2) return d1;
    else return d2;
}

错误:对distance 的引用不明确。

没有命名空间std的工作代码:

#include<iostream>

struct distance
{
    int feet;
    int inches;
};
distance foo(distance, distance);
int main()
{
    distance d1, d2;
    std::cout << "Input feet of d1: "; std::cin >> d1.feet;
    std::cout << "\nInput inches of d1: "; std::cin >> d1.inches;
    std::cout << "\nInput feet of d2: "; std::cin >> d2.feet;
    std::cout << "\nInput inches of d2: "; std::cin >> d2.inches;
    distance large = foo(d1, d2);
    std::cout << "The larger distance is: " << large.feet << "\'-" << large.inches << "\"";
}
distance foo(distance d1, distance d2)
{
    float temp1 = d1.feet + d1.inches/12;
    float temp2 = d2.feet + d2.inches/12;
    if(temp1>temp2) return d1;
    else return d2;
}

据我所知,命名空间 std 有 cout, cin 等对象。但它与结构有什么关系?为什么直接使用std::运行程序流畅,using namespace std报错?

【问题讨论】:

  • Error: Reference to distance is ambiguous. 你认为这可能意味着什么?
  • 因为有std::distance
  • @πάνταῥεῖ 谢谢。我不知道std命名空间中有一个距离结构。
  • 可惜这种东西在网上没有办法搜索到。
  • @user31782 std 命名空间中还有很多其他常用词:function、plus、less、set、pair、copy、unique...

标签: c++ namespaces


【解决方案1】:

您不应该完全使用using namespace std;,因为这(甚至是文字)可能会发生。

在您的情况下,编译器不知道您指的是哪个distance:它可能是您自己的,也可能是std::distance

如果你想避免每次都写std::cout,你可以写using std:: cout。 这将告诉您的编译器在您使用 cout 时查看的位置。

【讨论】:

  • std::cout不是比using std:: cout短吗?
  • 不,你误会了。而不是using namespace std; 你写using std::cout; using std::endl;。然后您可以直接使用coutendl,而不必每次都添加前缀std::
  • 哦。这意味着我们不需要调用整个名称空间,而是可以告诉编译器添加某些元素,例如 coutcin,方法是使用 std::cout 而不是 using namespace std;
  • 没错。就像在@MikeCAT 的回答中一样
【解决方案2】:

如消息所示,distance 名称在 std::distance 和您定义的结构之间有歧义。

你可以写

using std::cin;
using std::cout;
// more using for identifiers from namespace std to use

而不是using namespace std;

【讨论】:

  • 谢谢。我不知道std命名空间中有一个距离结构。
猜你喜欢
  • 1970-01-01
  • 2017-06-29
  • 2023-03-12
  • 2014-10-15
  • 1970-01-01
  • 2011-01-14
  • 2012-05-07
  • 2011-01-05
  • 1970-01-01
相关资源
最近更新 更多