如何访问 C++ 来自它所在的类中的下标运算符?
其中,ClassA 有一个这样的运算符,它返回 ClassB:
class ClassA
{
public:
ClassA();
ClassB &operator[](int index);
}
如果我想从 ClassA 的构造函数中访问所述运算符,如下所示:
ClassA::ClassA()
{
// How do I access the [] operator?
}
目前,作为一种解决方法,我只是使用名为 GetAtIndex(int index) 的方法[] 运算符调用它,构造函数也调用它。
如果我能像 C# 一样访问它那就太好了:
// Note: This is C#
class ClassA
{
ClassB this[int index]
{
get { /* ... */ }
set { /* ... */ }
}
void ClassA()
{
this[0] = new ClassB();
}
}
注意:我正在使用 g++
Where, ClassA has an operator as such, that returns ClassB:
class ClassA
{
public:
ClassA();
ClassB &operator[](int index);
}
If I want to access said operator from within ClassA's constructor, as so:
ClassA::ClassA()
{
// How do I access the [] operator?
}
At the moment, as a work-around I'm just using a method called GetAtIndex(int index) which the [] operator calls, and so does the constructor.
It would be nice if I could access it in the same as as C# works:
// Note: This is C#
class ClassA
{
ClassB this[int index]
{
get { /* ... */ }
set { /* ... */ }
}
void ClassA()
{
this[0] = new ClassB();
}
}
Note: I'm using g++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
但请确保在使用操作符之前,该操作符可能依赖的任何成员数据都已完全构造完毕。
But make sure that whatever member data the operator may depend on is fully constructed before you use it.
两种不同的方式:
Two different ways:
还有一个方法,不知道有没有用...
Here's another way, not sure if it's useful...
你可以使用:
或:
但语法有点尴尬。 我通常创建另一个名为
get
的方法并使用它,例如:然后当你想使用它时,你可以说:
You can use:
or:
But the syntax is a little awkward. I usually make another method called
get
and use that, e.g.:Then when you want to use it you can just say:
尝试以下操作
Try the following