在C ++中定义函数以返回结构

时间:2020-01-17 01:41:54

标签: c++ function struct

using namespace std;
#include <iostream>
#include <cstring>

struct distance {
    int Kilometer;
    int Meter;
    int Centimeter;
};

distance add() {
}

int main() {
    return 0;
}

试图定义一个返回“距离”数据类型的函数。 尝试定义该功能时,我遇到“距离不明确”的问题。

2 个答案:

答案 0 :(得分:6)

@1202ProgramAlarm points out in the comments一样,这是一个绝不包含using namespace std;的经典原因。因为已经引入了std命名空间,所以编译器不确定distance的含义是:自定义struct distancestd::distance,因此“距离是模棱两可的”。

最简单,最好的解决方法是不使用using namespace std。当然,您可能会花一些时间额外编写std::,但您可以避免这些头痛。

您也可以将struct重命名为Distance,也可以用::distance add()来限定它

答案 1 :(得分:4)

更改结构名称,在任何名称空间中定义它,或者不要使用using namespace std;,因为distance()名称空间中已经有一个名为std的函数。

#include <iostream>
#include <cstring>

namespace myNamespace{

    struct distance {
        int Kilometer;
        int Meter;
        int Centimeter;
    };

    distance add() {

        return distance();
    }
}

using namespace std;

int main() 
{
    myNamespace::distance d1;
    d1 = myNamespace::add();

    return 0;
}

通常using namespace std;是不正确的做法,请参见 Why is "using namespace std;" considered bad practice?