我一直在读一本C ++书,发现了这两个功能:
int &Array::operator []( int subscript ) // first
{
//code
return ptr[ subscript ];
}
int Array::operator[]( int subscript ) const //second
{
//code
return ptr[ subscript ]; // value return
}
Run Code Online (Sandbox Code Playgroud)
这个想法是创建一个Array对象并访问一些私有成员,例如:
Array myArray;
cout << myArray[ 2 ];
Run Code Online (Sandbox Code Playgroud)
但是我没有得到这些函数之间的区别,基本上是因为每次我键入“ cout << myArray [2]”之类的东西时,都会调用第一个函数。那么,第二个函数何时调用?第二项功能有效吗?
c++ ×1