0

我很难从另一个班级访问一个班级的成员。我已经宣布了两个班级。第一个是Form1,第二个是packet_class。该类的较短版本如下。我的问题是尝试从 packet_send_data 类更新 serialPort1。如何访问 serialPort1 对象,以便可以通过 packet_class::packet_send_data 发送数据?我尝试将引用 serialPort1 传递给 packet_class 实例化的 packet_class 对象,但没有成功。
感谢您的帮助(最好使用简单的代码示例)。
谢谢

namespace Form_Example {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

public ref class Form1 : public System::Windows::Forms::Form
{
    //Form Initialisation ETC
public:
    Form1(void)
    {
        this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this->components));
    }
protected:
public: System::IO::Ports::SerialPort^  serialPort1;
};

}

packet_class 如下

ref class packet_class
{
public:
    //Constructor Prototype
packet_class(void);
void packet_send_data(void);
String^ data_to_send; // Create an array to store 100 integers
};

//Packet_class Prototype
packet_class::packet_class(void)
{
 data_to_send="SEND ABC";
}

void packet_class::packet_send_data(void)
{
    //I want to access serialPort in the packet_class function here
    //serialPort1->Write(data_to_send);
}
4

1 回答 1

1

如果Form1是实例化的packet_class,只需将其作为参数传递给构造函数。

ref class packet_class
{
    SerialPort^ serial;

    packet_class(SerialPort^ serial)
    {
        this->serial = serial;
        data_to_send="SEND ABC";
    }
};

// Somewhere in Form1....
packet_class packet = gcnew packet_class(this->serialPort1);
于 2013-01-06T06:10:10.053 回答