error: passing xxx as 'this' argument of xxx discards qualifiers的解决办法

问题:

在controller.cpp的头文件controller.h中,有定义:

class Controller {
public:
    explicit Controller(const string uart_port);
    ~Controller();
    const SDCard& GetSDCard() const;
    const UartUsb& GetUart() const;
private:
    SDCard sdcard_;
    UartUsb uart_;
};
其中类UartUsb的声明为:

class UartUsb {
public:
    UartUsb();
    explicit UartUsb(const string uart_port);
    ~UartUsb();
    int OpenPort(const char *com_port);
    int SetComConfig(int baud_rate, int data_bits, char parity, int stop_bits);
    void ReadUart(char* buf_rd);
    void WriteUart(char* buf_wr);
private:
    string uart_port_;
    int fd_uart_;
};


在sensor_reader.cpp中用到了GetUart()函数:

void* SensorReader::Run() {
    main_ctrlr = static_cast<Controller*>(GetArg());
    time_t upload_time = 0;
    bool en_upload_sdcard_status = false;
    while (!IsStop()) {
        // Upload sdcard status only once
        if (en_upload_sdcard_status) {
             en_upload_sdcard_status = false;
        }

        // Enable uploading sdcard status
        time(&now_time);
        if ((now_time - upload_time) >= main_ctrlr->GetUploadInterval()) {
            upload_time = now_time;
            en_upload_sdcard_status = true;
        }

        // Store sdcard status into data_.buf
        main_ctrlr->GetUart().ReadUart(main_ctrlr->GetDataBuffer().buf);
        trim(main_ctrlr->GetDataBuffer().buf);

    }

    return NULL;
}


编译时出现如下错误提示:

hxtcdt@hxtc-desktop:~/hwsvn/2fw/01prj_mms/s3c6410/src/trunk$ make clean;make
arm-linux-g++ -g3 -Wall -O2  -c controller.cpp -o controller.o
arm-linux-g++ -g3 -Wall -O2  -c main.cpp -o main.o
arm-linux-g++ -g3 -Wall -O2  -c sdcard.cpp -o sdcard.o
arm-linux-g++ -g3 -Wall -O2  -c sensor_reader.cpp -o sensor_reader.o
sensor_reader.cpp: In member function 'virtual void* SensorReader::Run()':
sensor_reader.cpp:83: error: passing 'const UartUsb' as 'this' argument of 'void UartUsb::ReadUart(char*)' discards qualifiers
make: *** [sensor_reader.o] 错误 1
hxtcdt@hxtc-desktop:~/hwsvn/2fw/01prj_mms/s3c6410/src/trunk$


解决办法:

1。GetUart()返回的是const UartUsb对象;

因此当const UartUsb对象调用ReadUart()时,编译器检测到了问题。

也就是说,对一个const对象调用non-const成员函数是不允许的,因为non-const成员函数不保证一定不修改对象。

因此编译器做出一个安全的假定,假定ReadUart()会试图修改UartUsb对象,而与此同时,该UartUsb对象是const对象,所有试图修改const对象的都会报error。

2。 解决办法是将ReadUart()函数改为const函数:

    void ReadUart(char* buf_rd) const;


修改之后,问题解决。


你可能感兴趣的:(类,编译器)