返回引用C ++ / SystemC的类方法

时间:2015-06-14 13:06:08

标签: c++ systemc

要将用户定义的数据类型传递到SystemC通道模板,需要将这些数据类型定义为实现不同类型的运算符<<===的类。

我需要定义一个sc_fifo,例如:

sc_fifo<route_t>

为了使其正确,必须编写route_t数据类型,如下例所示。

class route_t
{
    public: 
    route_dir_t                     route_dir; 
    unsigned int                    vc_index; 

    // methods allowing the structure to be passed into SystemC channels
    // constructor
    route_t(route_dir_t _route_dir, unsigned int _vc_index) {
        route_dir = _route_dir; 
        vc_index  = _vc_index; 
    }

    inline bool operator == (const route_t& _route) const {
        return (route_dir == _route.route_dir && vc_index == _route.vc_index); 
    }

    inline route_t& operator = (const route_t& _route) {
        route_dir = _route.route_dir; 
        vc_index  = _route.vc_index; 
        return *this; 
    }

}; // end class route_t 
  1. 为什么SystemC需要这样的实现?
  2. 为什么operator=需要返回对象本身的引用?它只是更新了内部成员。
  3. 是否可以将数据类型定义为struct,而不是使用实现所需运算符的内部方法?
  4. 为什么inline在此上下文中使用?
  5. 返回*this如何等效于在方法声明中按预期返回对象的引用?

2 个答案:

答案 0 :(得分:0)

operator=应该返回对类本身的引用,以便您可以执行以下任何操作。

a = b = c;
if (a = b) { } // check the resulting value of a
(a = b).foo();

虽然这些可能不是您希望做的事情,但它遵循一般准则,即用户定义的对象的行为方式与内置对象的行为方式相同。

至于返回引用,您必须确保不返回对本地对象的引用,但它具有预期的语义。

答案 1 :(得分:0)

请看以下内容:

Myclass a, b, c;

a=b=c=otherMyclass;

要使其工作,每个operator=必须返回链中下一个要使用的引用。

此外,您通常应该检查作业本身不是

    inline route_t& operator = (const route_t& _route) {
   if (&_route != this)
   {
        route_dir = _route.route_dir; 
        vc_index  = _route.vc_index; 
        return *this; 
    }
}

这将处理:

   a=a;
相关问题