c++ - Visual C++ CLR 窗体项目。为函数使用单独的 c++ 文件

标签 c++ visual-c++

我有一个 Windows 窗体项目。我不想将所有函数和回调与所有自动生成的代码一起放在表单头文件中,而是希望将它们放在一个单独的 c++ 文件中。

我找到了这篇回答问题的帖子,但是我无法让它工作。我一定是遗漏了什么:How to use a separate .cpp file for my event function definitions in windows forms?

在我单独的 c++ 文件中,我尝试了以下操作:

#include "stdafx.h"
#include "DeltaForm.h"

namespace DeltaControl
{
    // Search for all serial ports and add them to the port combobox
    void searchPorts(void)
    {
        array<Object^>^ portsArray = SerialPort::GetPortNames();
        this->cbPort->Items->AddRange( portsArray );
    }

}

给出输出:

    1>test.cpp(10): error C2355: 'this' : can only be referenced inside non-static member functions
    1>test.cpp(10): error C2227: left of '->cbPort' must point to class/struct/union/generic type
    1>test.cpp(10): error C2227: left of '->Items' must point to class/struct/union/generic type
    1>test.cpp(10): error C2227: left of '->AddRange' must point to class/struct/union/generic type

还有这个:

#include "stdafx.h"
#include "DeltaForm.h"

namespace DeltaControl
{
    // Search for all serial ports and add them to the port combobox
    void DeltaForm::searchPorts(void)
    {
        array<Object^>^ portsArray = SerialPort::GetPortNames();
        this->cbPort->Items->AddRange( portsArray );
    }

}

输出:

1>test.cpp(7): error C2039: 'searchPorts' : is not a member of 'DeltaControl::DeltaForm'
1>          f:\documents\cloud\projects\deltarobot\deltarobotcontrol_vcpp\deltacontrol\deltacontrol\DeltaForm.h(16) : see declaration of 'DeltaControl::DeltaForm'
1>test.cpp(10): error C2355: 'this' : can only be referenced inside non-static member functions
1>test.cpp(10): error C2227: left of '->cbPort' must point to class/struct/union/generic type
1>test.cpp(10): error C2227: left of '->Items' must point to class/struct/union/generic type
1>test.cpp(10): error C2227: left of '->AddRange' must point to class/struct/union/generic type

这是我的表单头文件:http://pastebin.com/gGfMiwVr 它基本上只是生成的代码。

我觉得我在这里缺少一些非常基础的东西,但我的 C++ 技能还不是太好。

当我将上面第一个示例中的 searchPorts 函数放入表单头文件时,它编译没有问题。

编辑:

我刚刚解决了我自己的问题!我必须使用以下行在 DeltaForm 类中声明该函数:

private: void searchPorts(void);

因为单独的 c++ 文件没有定义类中的函数。是否可以将类拆分为多个 C++ 文件,这样我就不需要先声明该函数?或者,是否可以从类外部引用表单对象?

最佳答案

您的问题可能与 CLR 无关。

在您的第一个代码中,您展示了一个免费功能。自由函数不属于类(它不是 DeltaForm 的成员函数),因此无法访问“this”指针。它不与类的实例相关联,或者根本不与类相关联。

在你的第二个代码中,你可能更接近你想要的,但你很可能没有在类中声明 searchPorts 成员函数。

您需要在类头中添加声明:

class DetalForm
{
    /* ... */
    void DeltaForm::searchPorts(void);
    */ ... */
};

不要忘记分号。

类头中的声明没有主体。正文实际上是您的(第二个)代码片段。

关于c++ - Visual C++ CLR 窗体项目。为函数使用单独的 c++ 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21049218/

相关文章:

c++ - 使用线程传递指针时出错

c++ - 从项目 VS 2015/2017 中删除 math.h

c++ - ld : entry point (start) undefined. 通常在 crt1.o 中用于架构 x86_64

c++ - Visual C++ 异或加密错误

c - VS2017 编译器为除法/余数对发出 2 个除法指令

c++ - 使用三个参数重载 operator new 和 operator delete

opencv - VS2013 + Win7 中缺少 MSVCP140.dll

c++ - Visual C++无法写入exe

c++ - 解析函数中的命令行参数

c++ - 构造一个改变混合基类的类型