运算符重载中的隐式构造?
是否可以使用带有运算符的显式构造?
就像这个例子一样(这当然不起作用):
class myFoo {
public:
double x, y;
myFoo(double, double);
void operator [] (myFoo);
};
int main() {
myFoo f1(0.0, 1.1);
f1[ {9.9, 10.0} ]; /// or whatever syntax to use, does not work
f1.operator[] ( {9.9, 10.0} ); /// works !
}
Is it possible use in-explicit constructing with operators ?
Just like in this example (which does of course not work):
class myFoo {
public:
double x, y;
myFoo(double, double);
void operator [] (myFoo);
};
int main() {
myFoo f1(0.0, 1.1);
f1[ {9.9, 10.0} ]; /// or whatever syntax to use, does not work
f1.operator[] ( {9.9, 10.0} ); /// works !
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
C++11 允许将初始值设定项列表传递给重载的
运算符[]
(请参阅 13.5.5)。您需要类似的内容
,这将与
f1[ {9.9, 10.0} ];
的原始语法相匹配。C++11 allows an initializer list to be passed to an overloaded
operator []
(see 13.5.5).You'd need something like
That would match your original syntax of
f1[ {9.9, 10.0} ];
.嗯...
f1[myFoo(9.9, 10.0)];
?需要一个合理的
operator[]
(即期望一个const myFoo&
绑定到临时变量)。hmm...
f1[myFoo(9.9, 10.0)];
?requires a reasonably sane
operator[]
(i.e. expects aconst myFoo&
to bind to the temporary).不,在当前的 C++03 或即将推出的 C++11 标准中使用
operator []
是不可能的。但是,您可以使用一些奇怪的语法来利用operator []
来实现相同的目的:其中
operator []
如下:No this is not possible using
operator []
in current C++03 or upcoming C++11 standard. However, you can exploitoperator []
with some weird syntax to achieve the same:where the
operator []
is as,是的,它确实适用于当前的代码。无论您使用“[]”实现什么(我所做的就是返回类内数组中索引处的值。因此该类现在可以用作数组类型)运算符所有需要完成的操作确保您传入 const 引用并且不进行任何更改。
会工作的。
yes it does work with the current code. Whatever might be your implementation with the '[]' (all I have done is to return the value at the index in an array inside a class. So the class can now be used as an array type) operator all that needs to be done to make sure that you pass in a const reference and make no changes are done.
Will work.
您的代码在 C++11(g++ 版本 4.5.2)中运行良好。你只需说
而不是
Your code works fine in C++11 (g++ Version 4.5.2). You just have to say
instead of