强制转换运算符-参考还是不参考 [英] cast operator - to reference or not to reference

查看:66
本文介绍了强制转换运算符-参考还是不参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,假设我有这样的事情:

OK chaps, assume I have something like this:

typedef std::vector<cmyclassone*> tClassOneVect;

class CMyClassTwo
{
   tClassOneVect m_MyData;
public:
   operator const tClassOneVect() const { return m_MyData; }
   operator tClassOneVect() { return m_MyData; }
}

我已经重载了强制转换运算符,因此可以将CMyClassTwo的实例强制转换为tClassOneVect.好,到目前为止和我在一起吗?

所以我的问题是:我是否应该像这样声明类型转换运算符:

I''ve overloaded the cast operator so I can cast an instance of CMyClassTwo into tClassOneVect. OK, with me so far?

So my question is this: Should I declare the cast operator functions like this:

operator tClassOneVect() { return m_MyData; }


或像这样:


or like this:

operator tClassOneVect&() { return m_MyData; }


请在此处注意引用(&).

您的想法是什么?
Jim


Note the reference (&) here.

What are your thoughts chaps?
Jim

推荐答案

Jim,

这两个运算符的返回类型不同.

-operator tClassOneVect() { return m_MyData; }m_MyData构造一个临时 tClassOneVect(使用tClassOneVect副本构造函数)并返回它:调用者可以对返回的副本执行任何操作,而不会更改原始副本. br/>
-operator tClassOneVect&() { return m_MyData; }返回此实例 CMyClassTwo::tClassOneVect引用.调用方可以对其进行修改,并且只要此CMyClassTwo实例都可以保留.

-第三种可能性:operator const tClassOneVect&() { return m_MyData; }将返回对 CMyClassTwo::tClassOneVect实例的const(只读)引用.呼叫者可以使用它,但不能修改它.

欢呼声,
AR
Hi, Jim,

The two operators have different return types.

- operator tClassOneVect() { return m_MyData; } constructs a temporary tClassOneVect from m_MyData (using tClassOneVect copy constructor) and returns it: caller can do anything on the returned copy, it will not change the original.

- operator tClassOneVect&() { return m_MyData; } returns a reference to this instance of CMyClassTwo::tClassOneVect. Caller can modify it, and it will persist as long as this instance of CMyClassTwo.

- There is a third possibility: operator const tClassOneVect&() { return m_MyData; } which will return a const (read-only) reference to this instance of CMyClassTwo::tClassOneVect. Caller can use it but not modify it.

cheers,
AR


这篇关于强制转换运算符-参考还是不参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆