c++ - 运算符的定义

标签 c++ class operators

我正在尝试定义一些运算符。

我是根据这个文档做的:

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/

相关文章:

python - NameError 在字典理解中使用 eval

c++ - 检查 C++11 中运算符是否存在的最佳方法

Python "or"在 Swift 中等效?

c++ - C++中使用成员函数删除对象

c++ - 类方法包含相同的类对象

javascript - React 中 prevstate 的对象

python - 定义许多相同类型的对象的内存效率更高的方法

c++ - 如何覆盖 C++ 类中的 bool 运算符?

c++ - 使用 C++ 风格与 C 风格编写 bmp-header

c++ - LNK2019未解析的外部符号求助