在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.*/
在c++中:
初始化:当编译器需要初始化一个新建的对象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)
这时,程序员需要自己写拷贝构造函数,并重载赋值运算符。DblStack类的拷贝构造函数:
// 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];
}
调用这个拷贝构造函数初始化对象时候,会用new运算符动态分配一些内存给item变量。所以当再次给这个对象赋值的时候应该考虑到把分配给item的内存释放掉,再重新分配内存。所以应该这样重载赋值运算符:
// 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;
}