从.cpp文件中定义标签(在标头中)

Defining a label (in a header) from a .cpp file

本文关键字:标签 cpp 文件 定义      更新时间:2023-10-16

我在尝试在头文件之外定义标签时遇到了一点问题。三天前我才开始尝试学习C++,所以我可能在这里犯了一个非常明显的错误,我没有注意到。到目前为止,我还没有设法让它工作。

我想在 MIDCSrc.cpp 中定义文本,而标签的声明在 MIDC.h 中。到目前为止,我在 MIDC.h 中所做的是:

*MIDC.h*
#include "MIDCSrc.cpp"
*VS Auto-generated code*
private: System::Windows::Forms::Label^  label1;
*VS Auto-generated code*
private: System::Void label1_Click(System::Object^  sender, System::EventArgs^  e)
{
textfunc2(label1);
}

在 MIDCSrc 中.cpp是:

#include "MIDC.h"
namespace MIDC
{
void textfunc2(System::Windows::Forms::Label^ aLabel)
{
aLabel->Text = "Wow!";
}
}

(我正在使用Visual Studio 2017社区(

问题是,我什至无法测试它以看到它惨败,因为它给了我一个"错误 C2084 函数'void MIDC::textfunc2(System::Windows::Forms::Label ^(' 已经有一个正文">

正如我所说,如果这是一个明显的错误,我很抱歉,但我无法理解这个可爱的错误。如果除了正文错误之外的代码有什么问题(我知道有问题(,如果可能的话,告诉我。必须解决这个问题。

感谢谁回复:-(

尝试 user4581301 提到的建议:"标头保护"。这可以防止递归包含文件。这很简单:

#ifndef _MIDC_H
#define _MIDC_H
// here go the contents of MIDC.h
#endif

在 CPP 文件中执行相同的操作:

#ifndef _MIDCSRC_CPP
#define _MIDCSRC_CPP
// here goe the contents of MIDCSrc.cpp
#endif

#define 符号的选择是任意的。我在这里选择的名字只是常见的做法。诀窍是,仅当未定义此符号时,才会包含文件的内容 - 这是默认情况。#ifndef 身体的第一步是 #define 它,因此 #ifndef 条件只满足一次。