运算符重载不从文件中提取覆盖值

Operator Overloading not extracting overrided value from file

所以,我吃了不少苦头。我正在尝试创建 2 个重载函数,一个使用插入运算符输入文件,另一个使用提取运算符从文件中提取值。

代码示例 1:显示 class 个成员。

    class OUSB          
{
private:

    unsigned short PORTB;

public:
    OUSB() { };

    char command[256];

    // Example of Interface methods (These can be changed....)
    unsigned short writePORTB(unsigned short newValue);

    unsigned short readPORTB();

    unsigned short runOUSBcommand(const char* command);

    // you may choose to implement operator overloaded functions for read and write functions for portb
    void operator<<(const unsigned short &val); // write portb
    void operator>>(unsigned short &val);       // read portb   
};

代码示例 2:显示每个成员或至少大多数成员的定义。

unsigned short OUSB::runOUSBcommand(const char* command)
{
    FILE* fpipe;
    char line[256];
    fpipe = (FILE*)_popen(command, "r"); // attempt to open pipe and execute a command 
    if (fpipe != NULL) // check that the pipe opened correctly
    {
        while (fgets(line, sizeof(line), fpipe))
        { // do nothing here, or print out debug data
        //cout << line; // print out OUSB data for debug purposes
        }
        _pclose(fpipe); // close pipe
    }
    else cout << "Error, problems with pipe!\n";
    int ousbOP = (int)atoi(line);
    return ousbOP;
}

void OUSB::operator<<(const unsigned short& val)
{
    OUSB hello;
    hello.writePORTB(val);
}

void OUSB::operator>>(unsigned short& val)
{
    OUSB hello;
    hello.readPORTB();
}

unsigned short OUSB::writePORTB(unsigned short newValue)
{

    sprintf_s(command, "ousb -r io portb %d", newValue);
    PORTB = runOUSBcommand(command);
    return PORTB;
}
    unsigned short OUSB::readPORTB()
{
    PORTB = runOUSBcommand("ousb -r io portb");
    return PORTB;
}

代码示例 3:最后,这是一段与函数对话的代码,同时从文件中插入和提取

int main(int argc, char* argv[])
{
    //--- When no parameters MUST print id string in CSV format. 
    if (argc == 1)  // no parameters print this line.
    {
        cout << "3719632,s3719632@student.rmit.edu.au,Neshant_Thiru" << endl;

        OUSB command;
        unsigned short val = 3;
        command << val;       // write value to portb 

        command.writePORTB(8);  // write 8 to portb 

        command >> val;       // read portb and save to                             // variable value 

        cout << "value = " << val << endl;

    }

所以在上面代码示例的 main 中,你可以看到 val = 3 是如何插入到文件中的,它意味着被另一个值 8 覆盖,如 [=14] 所示=].

那么从文件中提取的值应该显示覆盖的数字 8。但是,它仍然显示值 3。 所以我真的不确定,为什么它不提取覆盖的功能。

P.S。我正在使用名为 OUSB 的 USB 板而不是 Open-Usb-io

void OUSB::operator>>(unsigned short& val)
{
    OUSB hello;
    hello.readPORTB();
}

您没有使用参数 val,而是丢弃了 hello.readPORTB() 的返回值。如果您在启用所有警告并将警告视为错误的情况下进行编译,那么发现此错误会容易得多。

您将读取的值存储在您立即丢弃的新对象中,并且不修改参数。

应该让*this进行读取和写入,读取时需要将值存储在参数中:

void OUSB::operator<<(const unsigned short& val)
{
    writePORTB(val);
}

void OUSB::operator>>(unsigned short& val)
{
    val = readPORTB();
}