从命名空间内的 class 调用函数?

calling a function from a class inside a namespace?

我写了一个代码,其中 class 存在于命名空间中。

这是头文件:如您所见,class 是在命名空间内创建的,在 frileg.h.

namespace frileg
{
    class legeplads
    {
    public:
        int x;
        int y;
        int z;
        void print();
    };
}

然后我还在 legeplads.cpp:

中定义了函数 print()
void frileg::legeplads::print()
{
    std::cout << "pos: {" << x << ", " << y << ", " << z << "}" << std::endl;
}

但是当我 运行 主函数中的代码时,我得到一个错误:“对 `frileg::legeplads::print()' 的未定义引用:"

int main(){

    legeplads a;
    a.x = 1;
    a.y = 2;
    a.z = 3;
    a.print();
    return 0;
}

我能够使用以下方法使它正常工作。

  1. 在 VSCode 中创建一个新文件夹。我将它命名为 SO_66629443_20210315 并放在我的 X:\test 文件夹中

  2. 添加 3 个文件。

  3. 修复丢失的包含。 legeplads.cpp 需要 #include <iostream>#include "frileg.h"main.cpp 需要 #include "frileg.h"

  4. 修改main.cpp构造a时使用frileg命名空间;使用 frileg::legeplads a; 而不是 legeplads a;

所以此时文件看起来像:

main.cpp

#include "frileg.h"

int main()
{

    frileg::legeplads a;
    a.x = 1;
    a.y = 2;
    a.z = 3;
    a.print();
    return 0;
}

legeplads.cpp

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

void frileg::legeplads::print()
{
    std::cout << "pos: {" << x << ", " << y << ", " << z << "}" << std::endl;
}

frileg.h

namespace frileg
{
    class legeplads
    {
    public:
        int x;
        int y;
        int z;
        void print();
    };
}
  1. 修改 tasks.json 以编译 1 个以上的文件,如此处文档所述:https://code.visualstudio.com/docs/cpp/config-mingw#_modifying-tasksjson

所以 tasks.json 文件看起来完全像:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\msys64\mingw64\bin\g++.exe",
            "args": [
                "-g",
                "${workspaceFolder}\*.cpp",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\msys64\mingw64\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

请注意,我在安装 mingw 时使用的是 msys2。我使用这些说明安装了它:https://www.msys2.org/

最后在 VSCode 中执行程序如下所示:

PS X:\test\SO_66629443_20210315>  & 'c:\Users\dresc\.vscode\extensions\ms-vscode.cpptools-1.2.2\debugAdapters\bin\WindowsDebugLauncher.exe' '--stdin=Microsoft-MIEngine-In-gtfgey3y.olb' '--stdout=Microsoft-MIEngine-Out-l2sggqju.oz3' '--stderr=Microsoft-MIEngine-Error-zgahgwi3.zwy' '--pid=Microsoft-MIEngine-Pid-0mc3zqbv.bqm' '--dbgExe=C:\msys64\mingw64\bin\gdb.exe' '--interpreter=mi'    
pos: {1, 2, 3}