简体   繁体   English

C ++函数已定义?

[英]C++ Function already defined?

At the top of a cpp file, I have 在cpp文件的顶部,我有

namespace PQL {
    class Synonym {
    ...
    public:
        ...
        int size();
    };
}

// removing the below chunk makes it work
int Synonym::size() {
    return ids.size();
}

Why does the bottom chunk make the code fail? 为什么最底层的代码会使代码失败? I am creating the implementation of the function? 我正在创建函数的执行? Other functions defined a similar way works. 其他功能定义了类似的工作方式。

UPDATE : 更新

Expired (dead) link 过期(无效)链接

The error I got looks like: 我得到的错误看起来像:

Error 1 error LNK2005: "public: int __thiscall PQL::Synonym::size(void)" (?size@Synonym@PQL@@QAEHXZ) already defined in main.obj H:\\Dropbox\\Sch\\CS3202\\SPA_CPP\\SPA\\pql.obj

Because Synonym isn't a name in global scope. 因为Synonym不是全局范围内的名称。

Either use 无论使用

int PQL::Synonym::size() {
    return ids.size();
}

or implement the method inside the namespace. 或在命名空间内实现方法。

From your comments, I put this together: You put everything in a single Cpp file and include that file in different other files. 根据您的评论,我将其组合在一起:您将所有内容都放在一个Cpp文件中,并将该文件包含在其他文件中。 Each of those files compiles, and each of those files has an implementation of PQL::Synonym::size() . 这些文件中的每个文件都进行编译,并且每个文件都具有PQL::Synonym::size() When linking, the linker sees all those definitions and doesn't know which one to choose. 链接时,链接器会看到所有这些定义,并且不知道选择哪个定义。

Split your code into header and source files and just include the header in the other files. 将代码分为头文件和源文件,仅将头文件包含在其他文件中。

Its because your code is in a header file and being included in multiple compilation units: 这是因为您的代码在头文件中,并且包含在多个编译单元中:

    inline int Synonym::size() {
//  ^^^^^^^
        return ids.size();
    }

Adding inline tells the linker that there may be multiple definitions. 添加内联告诉链接器可能有多个定义。

Note: The keyword 'inline' has nothing to do with code inline-ing in modern compilers. 注意:关键字“ inline”与现代编译器中的代码内联无关。

As a very important note. 作为一个非常重要的说明。

Your header file contains: 您的头文件包含:

 using namespace std;
 // and
 using namespace PQL;

This is a very bad idea. 这是一个非常糟糕的主意。 You are now forcing this on anybody that uses your code. 现在,您将对所有使用您的代码的人强制执行此操作。 I would never use your header file as it would contaminate my code and cause unforeseen problems. 我永远不会使用您的头文件,因为它会污染我的代码并导致无法预料的问题。 It is OK to do this in your own source files (when you know and understand the issues) but you should never force this on other developers. 可以在自己的源文件中进行此操作(当您了解并理解这些问题时),但是绝对不要强加于其他开发人员。

See: Why is "using namespace std" considered bad practice? 请参阅: 为什么“使用命名空间标准”被认为是不良做法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM