操作员重载不从文件中提取被覆盖的值。

问题描述 投票:0回答:1

所以,我遇到了一个相当棘手的问题。我试图创建两个重载函数,一个使用插入操作符输入文件,另一个使用提取操作符从文件中提取值。

代码示例1:显示类成员。

    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,[email protected],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;

    }

因此,在我的主内,在上面的代码示例中,你可以看到如何 val = 3 被插入到文件中,它的意思是被另一个值覆盖,这个值是8,如图所示。command.writePORTB(8).

那么从文件中提取的值应该显示被覆盖的数字8。但相反,它仍然显示值3。所以我真的不明白,为什么它不提取被覆盖的函数。

P.S.我使用的是一个叫作 OUSB 缩写为Open-Usb-io

c++ operator-overloading
1个回答
-1
投票

你把读取到的值存储在一个新的对象中,然后立即扔掉,而且你不修改参数。

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

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

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

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

你不需要使用参数 val 的返回值,但要丢弃 hello.readPORTB(). 如果你在编译时启用了所有的警告,并将警告视为错误,那么这个错误就会容易得多。

© www.soinside.com 2019 - 2024. All rights reserved.