如何使转换运算符返回引用和非引用
How to make conversion operator returning reference and non reference
我有一个模板类,看起来像:
template<class T>
class A
{
public:
operator T() const { return value;}
operator T&() { return value;}
private:
T value;
}
似乎从未调用运算符 T() 常量。即使在这样的声明中
const int a = myA;
其中 myA 是 A 的实例。上面的代码有问题吗?
仅当您定义类型为 const A<T>
的对象时,运算符才会生效。例如:
const A<int> myA;
int someInt = myA;
会打电话给operator T() const
.
而且,正如本杰明·林德利指出的那样,如果你通过const
引用访问对象,这当然是正确的。
相关文章:
- 如何通过引用返回对象
- 函数如何使用引用返回所需的数字?
- 如何防止引用返回的私有结构的突变
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 通过引用返回的变量的范围
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 运算符重载C++类中的引用返回
- C++对象引用返回不同的值
- 解释通过从函数引用返回数组的语法
- 具有引用返回类型的重写方法上的协变返回类型无效
- 为什么在通过引用返回运算符分配时取消引用'this'指针?
- 为什么我在函数中使用引用并通过引用返回它仍然有效?
- 直接在 C++ 中将值分配给引用返回类型
- C++当您取消引用指向类对象的指针,然后将其作为引用返回时,是否可以对此引用调用方法
- 可以通过常量引用返回默认参数的值吗?
- 按值与右值引用返回
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 当我使用按引用返回时,我不知道这些代码之间的区别
- 为什么通过引用返回向量比通过移动返回要快得多?
- 通过引用返回包含对象的向量