首页 文章

如何从C中的类文件运行函数?

提问于
浏览
1

我试图从类文件运行一个函数,但它不工作,我收到以下错误消息:错误LNK1120:1未解析的外部

错误LNK2019:函数_main中引用的未解析的外部符号“public:void __thiscall NS :: Class1 :: test(void)”(?test @ Class1 @ NS @@ QAEXXZ)

//Main.cpp

#include<iostream>
#include<string>
#include<Windows.h>
#include "Class1.h"

int main(){
    NS::Class1 E;
    E.test();
    return 0;
};
//Class1.cpp

#include <Windows.h>
#include <string>
namespace NS{
class Class1{
        Class1(){
            OutputDebugString(L"Created.");
        }

        void test(){
            OutputDebugString(L"Hello World");
        }
    };
}
//Class1.h

#ifndef _Class1_H_
#define _Class1_H_
namespace NS{
    class Class1{
        public:
            void test();
        };
}
#endif

3 回答

  • 6

    在源文件中,您将重新定义类,而不是定义其成员函数 . 这将给出未定义的行为,因为您只允许定义一次类 . 源文件看起来应该更像:

    #include "Class1.h"
    #include <Windows.h>
    
    NS::Class1::Class1(){
        OutputDebugString(L"Created.");
    }
    
    void NS::Class1::test(){
        OutputDebugString(L"Hello World");
    }
    

    您还需要修改标头中的类定义,因为它不会声明构造函数 .

    此外,请确保您的项目正在编译和链接两个源文件 .

  • 1

    您的头文件包含包含保护的保留ID,并且错过了构造函数的声明 . 它应该如下所示:

    #ifndef CLASS1_H
    #define CLASS1_H
    
    namespace NS {
    
    class Class1
    {
    public:
        Class1();
        void test();
    };
    
    }
    #endif
    

    该类的定义不应该包含 class 声明,它应该 include 它,并且看起来应该更像这样:

    #include <Windows.h>
    
    #include "Class1.h"
    
    namespace NS {
    
    Class1::Class1()
    {
        OutputDebugString(L"Created.");
    }
    
    void Class1::test()
    {
        OutputDebugString(L"Hello World");
    }
    
    }
    
  • 0

    我认为您的.cpp文件可能会导致此问题 . 由于您已使用类成员声明在头中创建了类定义,因此只需在Class1.cpp文件中导入Class1.h标头,然后定义成员函数,然后定义它们的行为 .

    所以也许试试:

    #include <Class1.h>
    
    NS::Class1::Class1(){}//constructor
    
    void NS::Class1::test(std::cout << "hi"){}
    

相关问题