返回引用 C++/SystemC 的类方法
Class method returning reference 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
- 为什么 SystemC 需要这样的实现?
- 为什么
operator=
需要返回对对象本身的引用?它只是更新内部成员。 - 是否可以将数据类型定义为
struct
,而不是使用实现所需运算符的内部方法? - 为什么在这种情况下使用
inline
? - 返回
*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;
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 检查类方法中是否(此 == nullptr)
- 从基类实例调用派生类方法而不进行强制转换
- 函数从唯一代码调用正确的子类方法
- C++ - 如何在不静态的情况下将回调绑定到类方法?
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- 返回引用 C++/SystemC 的类方法