简体   繁体   English

无法在 Visual Studio 2022 中包含 .cpp 和 .h 文件

[英]Cannot include .cpp and .h files in Visual Studio 2022

I have created a class Dialog and separated it into.cpp (Dialog.cpp) and.h (Dialog.h).我创建了一个 class Dialog 并将它分成.cpp (Dialog.cpp) 和.h (Dialog.h)。 My cpp file looks like this:我的 cpp 文件如下所示:

#include "Dialog.h"
#include <iostream>
using namespace std;

namespace Model1
{
    void Dialog::initialize ()
    {
          cout << "initialization";
    }
}

And here is my h file:这是我的 h 文件:

using namespace std;
class Dialog
    {
        public:
            void initialize ();
    };

When I debug the code in visual studio 2022 I get this:当我在 visual studio 2022 中调试代码时,我得到以下信息:

cannot open source file "Dialog.h"
name followed by '::' must be a class or namespace name
Cannot open include file: 'Dialog.h': No such file or directory ConsoleApplication1 
symbol cannot be defined within namespace 'Model1'  ConsoleApplication1

When I changed my header file to当我将 header 文件更改为

using namespace std;
namespace Model1 {
    class Dialog
    {
    public:
        void initialize();
    };
}

And now I have these errors:现在我有这些错误:

cannot open source file "Dialog.h"
name followed by '::' must be a class or namespace name
Cannot open include file: 'Dialog.h': No such file or directory 

How can I fix the problem?我该如何解决这个问题?

The problem is that in the header file you've defined class Dialog in global namespace while you're trying to define the member function Dialog::initialize() in Model1 namespace.问题是在 header 文件中,您在全局命名空间中定义了 class Dialog ,而您试图在Model1命名空间中定义成员 function Dialog::initialize()

This will not work because the out-of-class definition for the member function of a class must be in the same namespace in which the containing class is .这将不起作用,因为class 的成员 function 的类外定义必须位于包含 class 的同一命名空间中

Thus, to solve this you can either define the class(in the header) in namespace Model1 or implement the member function(in the source file) in global namespace.因此,要解决此问题,您可以在命名空间Model1中定义类(在标头中)或在全局命名空间中实现成员函数(在源文件中)。 Both these methods are shown below:这两种方法如下所示:

Method 1方法一

Here we define the class in namespace Model1 in the header and leave the source file unchanged .这里我们在header的命名空间Model1中定义class,源文件不变

dialog.h对话框.h

namespace Model1   //added this namepspace here
{
class Dialog
    {
        public:
            void initialize ();
    };
}

Working demo 1工作演示 1


Method 2方法二

Here we define the member function in global namespace in source file and leave the header file unchanged .这里我们在源文件的全局命名空间中定义了成员function,并保持header文件不变

dialog.cpp对话框.cpp

#include "Dialog.h"
void Dialog::initialize ()
{
      cout << "initialization";
}

Working demo 2工作演示 2

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

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