在 C++ 中重载 Subscript[] 运算符设置类的大小(量词)。
美好的一天,伙计们。
我有以下结构和类,
template <class T>
struct Node
{
T DataMember;
Node* Next;
};
template <class T>
class NCA
{
public:
NCA();
~NCA();
void push(T);
T pop();
void print();
void Clear();
private:
Node<T>* Head;
void* operator new(unsigned int);
};
我想用一个大小实例化该类,
即。 NCA[30] 就像任何数组一样
Good day guys.
I have the following struct and class,
template <class T>
struct Node
{
T DataMember;
Node* Next;
};
template <class T>
class NCA
{
public:
NCA();
~NCA();
void push(T);
T pop();
void print();
void Clear();
private:
Node<T>* Head;
void* operator new(unsigned int);
};
I would like to instantiate the class with a size
ie. NCA[30] as one would any array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不能。但是,您可以做几乎类似的事情:用括号初始化它,而不是方括号:
像这样实现它:
You can't. But, you can do something almost like that: initialize it with parenthesis, but not brackets:
Implement it like so:
如果编译器允许您在对象构造函数中使用括号,它如何知道您是要尝试创建大小为 30 的
NCA
还是大小为 30NCA
的数组物体? C++ 不允许您覆盖括号语法,除非您已经拥有对象后作为运算符。If the compiler were to allow you to use brackets in your object constructor, how would it know whether you were trying to make an
NCA
of size 30 or an array of 30NCA
objects? C++ does not allow you to override the bracket syntax, except as an operator once you already have an object.这并不完全是
operator[]
的工作原理。当您编写
NCA[30]
时,您正在编写type[30]
,要使用operator[]
,您需要一个实例:您可以做的是使用整数模板参数来指定大小,例如:
That's not quite how
operator[]
works.When you write
NCA[30]
you're writingtype[30]
, where as to useoperator[]
you need an instance:What you can do though is use an integer template parameter to specify the size, e.g.:
你不能。
您只能使用 ctor 来执行此操作,如下所示:
You can't.
You can only use the ctor to do it like: