我想知道常量成员函数在这种情况下是如何工作的......
自定义数组类:
class Array
{
private:
int m_size;
int *m_ptr;
// Utility function
void set_size( int size ); // Set size of array
public:
// Constructors
Array( int array_size ); // Default constructor
Array( const Array ©_array ); // Copy constructor
// Destructor
~Array() { delete [] m_ptr; };
int get_size() const { return m_size; }; // Get size of array
// Overloaded Operators
const Array &operator=( const Array &rhs );
}
const Array &Array::operator=( const Array &rhs )
{
if( this != &rhs )
{
if( this -> get_size() != rhs.get_size() )
{
delete [] m_ptr;
set_size( rhs.get_size() );
m_ptr = new int[ get_size() ];
}
for( int i = 0; i < get_size(); i++ )
{
this -> m_ptr[i] = rhs.m_ptr[i];
}
}
return *this;
}
我想知道重载的'='运算符如何首先声明常量?因为成员函数确实更改了当前对象的值。如果您正在使用此函数,只要当前对象本身不是常量,您就可以在赋值后更改对象的值。所以我想知道这个函数的声明是什么意思这样的呢?
答案 0 :(得分:1)
在我看来,这是一个错字或设计错误。返回引用应该没有const限定符。
Array &Array::operator=( const Array &rhs )
{
//...
}
答案 1 :(得分:1)
有一种思想流派认为operator=
应该返回一个const引用,以防止编译(a = b) = c
之类的代码。这种观点在C ++的早期更为常见,因为C不允许构造,人们希望C ++的行为方式相同。这些日子并不常见。