在c和c++中,赋值和初始化是不同的概念,很容易弄混淆。但是在c++中弄清这两个概念的不同很重要。
void f() { int x = 1; /* Initialization. */ int y = x; /* Initialization. * / y = 2; /* Assignment. */ x = y; /* Assignment. * / y = g(x); /* Assignment (y = temp; temp is <span style="font-family: Arial, Helvetica, sans-serif;">a temporary on the stack frame of f(). See return statement below. */ </span> } int g( int a) /* Initialization (int a = x). */ { int t = a+1; /* Initialization. */ return 2*t; /* Initialization (int temp =2* t, */ } /* where temp is as above. */
初始化和赋值的区别是:
赋值:新建对象,并第一次给它赋值
赋值:对象已经存在,给它赋值后覆盖原来的值
在C中初始化和赋值的区别:
常变量只能初始化,不能赋值
const int m = 5; /* Initialization required. */ m = 7; /* Illegal. */
double a[3] = {1,3,2}; /* Initialization optional. */ double b[3]; b = a; /* Illegal.*/
初始化:当编译器需要初始化一个新建的对象T(可以是struct也可以是class)时,他会调用T的构造函数进行初始化。如果需要拷贝其他对象进行新建T对象,那么就调用T的拷贝构造函数。
T( const T &x); // Initialize *this to a copy of x.
T &operator=( const T &x); // *this = copy of x
DblStack s, u; s.push(5); s.push(2); u.push(8); DblStack t = s; // Compiler invokes DblStack(s) // with this=&t. u = t; //Compiler invokes u.operator=(t)
// Copy constructor for class DblStack. Initializes *this // to a copy of s. DblStack( const DblStack &s) { height = s.height; allocSize = s.allocSize; item = new double[allocSize]; for ( int i = 0 ; i < height ; ++i ) item[i] = s.item[i]; }
// A nearly correct overloaded assignment operator for // class DblStack. Performs the assignment *this = s. void operator=( const DblStack &s) { delete[] item; height = s.height; allocSize = s.allocSize; item = new double[allocSize]; for ( int i = 0 ; i < height ; ++i ) item[i] = s.item[i]; }
x=x
s=t=u
所以,我们应该考虑在重载赋值运算符时加个判断,再返回一个对象。
// Corrected overloaded assignment operator for // class DblStack. Performs the assignment *this = s. DblStack &operator=( const DblStack &s) { if ( this != &s ) { delete[] item; height = s.height; allocSize = s.allocSize; item = new double[allocSize]; for ( int i = 0 ; i < height ; ++i ) item[i] = s.item[i]; } return *this; }