C++带有重载 = 运算符的包装器
我正在尝试围绕 int 开发一个非常简单的(目前)包装类,并希望重载 = 运算符以实现类似以下内容:
class IntWrapper
{
...
private:
int val;
}
int main ( )
{
IntWrapper a;
int b;
a = 5; // uses overloaded = to implement setter
b = a; // uses overloaded = to implement getter
}
我正在收集,但是这不能完成了。实现 setter 非常简单,例如:
class IntWrapper
{
...
IntWrapper& operator = (int rhs) { this.val = rhs; return *this; }
...
}
但是,从我收集的一些谷歌搜索来看,没有办法以这种方式执行 getter。我的理解是,这是因为 = 运算符只能被重写以将分配给变量,并且由于 int 是原始类型,我们无法重写其 = 的默认实现。这是正确的吗?如果没有,我该如何编写吸气剂?
如果这是正确的,有人对类似的东西有任何优雅的建议吗?我能找到的最接近的是重载转换运算符:
class IntWrapper
{
...
operator int( ) { return this.val; }
...
}
int main ( )
{
...
b = (int) a;
...
}
对我来说,这似乎毫无意义,因为它几乎不比简单的 getVal() 方法更好。
感谢您的任何建议!
I'm trying to develop a pretty simple (for now) wrapper class around int, and was hoping to overload the = operator to achieve something like the following:
class IntWrapper
{
...
private:
int val;
}
int main ( )
{
IntWrapper a;
int b;
a = 5; // uses overloaded = to implement setter
b = a; // uses overloaded = to implement getter
}
I'm gathering however that this can't be done. Implementing the setter is pretty straightforward, something like:
class IntWrapper
{
...
IntWrapper& operator = (int rhs) { this.val = rhs; return *this; }
...
}
However, from a bit of Googling I'm gathering there's no way to do the getter in this way. My understanding is that this is because the = operator can only be overridden to assign to a variable, and since int is a primitive type we cannot override its default implementation of =. Is this correct? If not, how do I go about writing the getter?
If that is correct, does anyone have any elegant suggestions for something similar? About the nearest I can find is overloading a conversion operator:
class IntWrapper
{
...
operator int( ) { return this.val; }
...
}
int main ( )
{
...
b = (int) a;
...
}
To me though that seems pretty pointless, as its barely any better than a simple getVal() method.
Thanks for any suggestions!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要强制转换来调用转换函数。 plain
也会调用它。这样,我就可以看到它比
getVal
函数使用起来更方便。虽然我一般不使用转换函数。我更喜欢显式的 getVal 函数。特别是考虑这个它很快就会失控......
You don't need a cast to invoke the conversion function. A plain
will invoke it too. That way, i can see how that's more convenient to use than a
getVal
function. Although i generally don't use conversion functions. I would prefer an explicitgetVal
function. In particular consider this oneIt quickly gets out of hand...
你建议的就是要走的路,我一直在用它。您不需要将 a 转换为 int 。编译器足够聪明,可以看到 b 是一个 int,它会自动为您调用运算符 int 强制转换运算符。
What you suggest is the way to go, and I use it all the time. You shouldn't need to cast a to an int. The compiler is smart enough to see the b is an int and it will automatically call the operator int cast operator for you.