我正在尝试定义一些运算符。
我是根据这个文档做的:
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
是否有应该定义两次的运算符?
我认为它是索引运算符。我对吗?我这样定义它:
int operator [] (const int power) const{
// here there is some code
}
假设我正确地实现了它,那么应该定义两次的运算符呢?
是否支持后续的东西?
a[1] = 3;
cout << a[1]; // I defined the << operator
感谢任何帮助!
最佳答案
I think that it's the index operator. am I right?
差不多。它称为下标运算符,它必须接受一个 单个参数。您的运营商接受两个,这使您的代码非法。
Does it support the next things?
假设您有一个正确编写的 operator []
(在不知道您的应用程序逻辑的某些上下文的情况下,我不知道如何编写一个),那么您提到的两个指令都应该得到支持。
然而,为了做到这一点:
a[1] = 3;
为了合法(如果返回基本类型),operator []
应该返回左值引用 - 因此,int&
而不是 int
。当然,这意味着左值引用绑定(bind)到的对象不能是本地对象或临时对象,因为那将意味着返回一个悬空引用。
int& operator [] (const int power) { // <== The function cannot be "const" if you
// ^ // are returning a non-const lvalue ref
// to a data member or element of a data
// member array
// here there is some code
}
您可能还需要下标运算符的 const
版本:
int operator [] (const int power) const {
// No need to use a int const& ^^^^^
// here, that is basically the This member function can be const, since it is
// same as returning an int by neither modifying the object on which it is
// value invoked, nor returns any non-const lvalue ref
to a data member or an element of data member
// here there is some code
}
关于c++ - 运算符的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132733/