Вопрос

I'm having difficulty accessing a member of one class from another class. I have declared two classes. The first is Form1, the second is packet_class. Shorter versions of the class are below. My problem is attempting to update serialPort1 from the packet_send_data class. How can I access the serialPort1 object so that I can send data out via packet_class::packet_send_data? I've attempted passing a reference serialPort1 to the packet_class instantiated packet_class object with no success.
Your help is appreciated (Preferably with a simple code example).
Thanks

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;
};

}

The packet_class is below

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);
}
Это было полезно?

Решение

If Form1 is the one that instantiates packet_class, just pass it as a parameter to the constructor.

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);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top