运算符的定义 [英] Definition of operators
问题描述
我试图定义一些运算符。
我根据这个文档做:
a href =http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html =nofollow> http://courses.cms.caltech.edu/cs11/是否有一个操作符应该定义两次?
$ b $ b
我认为它是索引操作符。我对吗?我定义它如:
int operator [](const int power)const {
//这里有一些代码
}
假设我正确实现它,定义两次?
它是否支持下面的事情?
[1] = 3;
cout<< a [1]; //我定义了<<运算符
任何帮助。
我认为它是索引操作符。我是对吗?
几乎。它称为下标运算符,并且必须接受一个单个参数。
它是否支持下面的功能?
假设你有一个正确的运算符[]
(不知道你的应用程序的逻辑的一些上下文我不能告诉
但是,为了这个:
a [1] = 3;
要合法(如果返回基本类型),
应返回一个左值引用 - 因此, int&
而不是 int
。当然,这意味着绑定了左值引用的对象不能是局部对象或临时对象,因为这意味着返回一个引用。
int&如果
// ^ //正在返回一个非常量的值$ ref
//到数据中,函数不能是const成员或数据元素
//成员数组
//这里有一些代码
}
您可能还需要一个 const
版本的下标运算符:
int operator [](const int power)const {
//不需要使用int const& ^^^^^
//这里,这基本上是成员函数可以是const,因为它是
//与返回一个int没有修改对象的它是
//值被调用,也不返回任何非常量值
到数据成员或数据成员的元素
//这里有一些代码
}
I am trying to define some operators.
I do it according to this documentation:
http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html
Is there an operator that should be defined twice?
I think that it's the index operator. am I right? I defined it such as:
int operator [] (const int power) const{
// here there is some code
}
Assuming I implement it correctly, what's about the operator that should have be defined twice?
Does it support the next things?
a[1] = 3;
cout << a[1]; // I defined the << operator
any help appreciated!
I think that it's the index operator. am I right?
Almost. It is called the subscript operator, and it must accept one single argument. Your operator accepts two, and that makes your code illegal.
Does it support the next things?
Supposing you have a properly written operator []
(without knowing some context from the logic of your application I cannot tell how to write one), then both the instructions you mention should be supported.
However, in order for this:
a[1] = 3;
To be legal (if a fundamental type is returned), operator []
should return an lvalue reference - therefore, int&
and not int
. Of course, this means the object to which the lvalue reference is bound cannot be a local object or a temporary, because that would mean returning a dangling reference.
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
}
You may also want a const
version of the subscript operator:
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
}
这篇关于运算符的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!