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

Class method returning reference C++/SystemC

本文关键字:类方法 SystemC 引用 C++ 返回      更新时间:2023-10-16

要将用户定义的数据类型传递到 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如何等效于在方法声明中按预期返回对对象的引用?

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

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

尽管这些可能不是您希望执行的操作,但它遵循一般准则,即让用户定义的对象的行为方式与内置对象的行为方式相同。

至于返回引用

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

查看以下内容:

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;