我无法让我的重载=
运算符正常工作。我有这样的课程。
SSLColumn::SSLColumn(int n){
m_capacity = n;
m_data = new int[m_capacity];
m_size = 0;
m_start = 0;
m_end = 0;
}
我现在重载的操作符就像这样
const SSLColumn& SSLColumn::operator=(const SSLColumn& rhs) {
m_capacity = rhs.m_capacity;
m_data = new int[m_capacity];
m_size = rhs.m_size;
m_start = rhs.m_start;
m_end = rhs.m_end;
for(int i = 0; i < m_size; i++)
m_data[i] = rhs.m_data[i];
return *this;
}
但由于某种原因它不起作用。我有什么遗漏或没有做错吗?
答案 0 :(得分:0)
成员变量m_size未在构造函数中初始化,因此for循环在重载运算符中不起作用。假设m_size = m_ capacity:
,请参阅此伪代码class SSLColumn {
int m_capacity;
int m_size;
int* m_data ;
public:
SSLColumn( int n);
const SSLColumn& operator=(const SSLColumn& rhs);
};
SSLColumn::SSLColumn( int n) {
m_capacity = m_size = n; // <--- SEE HERE ! ( m_size need some value later
m_data = new int[n];
}
const SSLColumn& SSLColumn::operator=(const SSLColumn& rhs) {
if( m_data == NULL) m_data = new int[m_capacity];
for (int i = 0; i < m_size; i++)
m_data[i] = rhs.m_data[i];
return *this;
}