重写 operator=

C++语言 码拜 8年前 (2016-05-29) 1224次浏览
//serialport.h
class SerialPort
{
public:
    SerialPort(boost::asio::io_service &ios, boost::asio::serial_port &port);
    SerialPort &operator=(const SerialPort &o); //重写 operator=
private:
    boost::asio::io_service &m_ios;
    boost::asio::serial_port &m_port;
};
//serialport.cpp
#include "serialport.h"
SerialPort::SerialPort(boost::asio::io_service &ios, boost::asio::serial_port &port): m_ios(ios), m_port(port)  //compile OK
{
}
//方式一 (结果编译不过去)
SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
    m_ios = &o.m_ios; //error! 
    m_port = &o.m_port; //error! 
    return *this;
}
//error: no match for "operator=" (operand types are "boost::asio::io_service" and "boost::asio::io_service*") m_ios = &o.m_ios;
//方式二 (结果编译不过去)
SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
    m_ios = o.m_ios; //error! Why?
    m_port = o.m_port; //error! Why?
    return *this;
}
//error: use of deleted function "boost::asio::io_service& boost::asio::io_service::operator=(const boost::asio::io_service&)" m_ios = o.m_ios;

问题: 本人应该怎么正确重写这个 operator= 呢?谢谢各位!

解决方案

5

SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
    this->~SerialPort();
    this->SerialPort(o.xxx, o.yyyy);
    return *this;
}

手动调用析构/构造函数

5

然而这么写还是错的

引用:

已解决。 引用:

SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
    this->~SerialPort();
    this->SerialPort(o.xxx, o.yyyy);//构造函数应该不能这么调用吧,没试过,不知道行不行
    return *this;
}

手动调用析构/构造函数

SerialPort &SerialPort::operator=(const SerialPort &o) //重写operator=
{
    this->~SerialPort();
    //直接调用,构造函数,重新构造对象本人,
     //用placement new ,似乎比较正常一点
    new(this) SerialPort(o.xxx, o.yyyy);
    return *this;
}

试试看

3

《C++编程思想》

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明重写 operator=
喜欢 (0)
[1034331897@qq.com]
分享 (0)