[英]Conversion vs subscript operator overload for class wrapping an array
I have a class wrapping an array and want to provide the typical subscript access to its users.我有一个包装数组的类,并希望为其用户提供典型的下标访问。
...
class C;
C c;
auto x = c[0];
...
I may both provide conversion我可能都提供转换
class C
{
int i[10];
public:
operator int*() { return i; }
};
and provide subscript operator overload并提供下标运算符重载
class C
{
int i[10];
public:
int& operator[](unsigned idx) {
// eventual out-of-bounds check
return i[idx];
}
};
Apart from OOB check, which one should be preferred?除了OOB检查,应该首选哪个?
If you just want to call operator[]
on the class C
, then just overload operator[]
.如果您只想在类C
上调用operator[]
,那么只需重载operator[]
。 Don't allow implicit conversion if not necessary.如无必要,不允许隐式转换。 If you provide operator int*
, something meaningless and dangerous will be allowed too.如果你提供operator int*
,一些无意义和危险的东西也会被允许。 eg例如
C c;
if (c) ...;
delete c;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.