相关内容不做赘余,仅就部分问题个人以前未理解内容记录
一、this和*this的区别。
之前理解为this为指针,那么this则指向this指针的地址,而*this则应该指向其指针所指向当前对象。
正解应该是:this指针指向当前对象的地址,即它是一个指向当前对象的指针。
*this为当前对象的复制或者当前对象本身,即根据对象返回值类型而定。当为引用时为后者,否则为前者
看起来似乎意思差不多,但仔细理解会发现二者差别还是较大
二、运算符[]重载
下面相关代码似乎看起来似乎没什么不同。但是运算符[]需要考虑的有其作为左值和右值的差别。
右值:即A = NUM[ I ]
这时重载只需要考虑i为合法区间即可(下面未处理)
左值:即NUM[ I ] ?= 123
这时我们需要考虑的问题是:当前内存中所存储的值是需要改变的,那么就存在赋值或复制的关系。下面代码之前一直纠结【】二者重载没有多大区别,问题就出在这里,因为Vector中已经定义了复制构造函数和拷贝赋值运算符
三、复制构造函数和拷贝赋值运算符的区别
当声明时进行初始化,为复制构造函数
int a = 1;
当声明之后有赋值运算,称为拷贝赋值运算符
int a;
a = 1;
以上例子虽然不是很合理,但意思如上(将以上例子改为对象)。虽然看起来只是概念性问题,但之前一直不理解
代码参照《C++语言导学》(2015年4月版,c++之父Bjarne Stroustrup新作);
#include <iostream> using namespace std; class Vector{ double *elem; int sz; public: Vector( int s ); ~Vector(){delete []elem; }; Vector( const Vector &a );//复制构造函数 Vector& operator=(const Vector &a );//拷贝赋值函数 double& operator[](int i); const double& operator[]( int i )const; int size() const; }; Vector::Vector( int s ):elem{ new double[ s ] }, sz{ s }{}; Vector::Vector( const Vector &a ):elem{ new double[ a.sz ] },sz{a.sz}{ for( int i = 0; i != sz; ++i ){ elem[ i ] = a.elem[ i ]; } } double& Vector::operator[]( int i ){ return elem[ i ]; } const double& Vector::operator[]( int i )const{ return elem[ i ]; } Vector& Vector::operator=( const Vector &a ){ double *p = new double[ a.sz ]; for( int i = 0; i != a.sz; ++i ){ p[ i ] = a.elem[ i ]; } delete []elem; elem = p; sz = a.sz; return *this; } int Vector::size()const{ return sz; } void bad_copy(Vector v1 ){ Vector v2 = v1; int len = v1.size(); /*test*/ for(int i = 0; i < len; ++i ){ cout << &v1[ i ] << " " << &v2[ i ] << endl; } cout <<"***********" << endl; v1[ 0 ] = 2; v2[ 1 ] = 3; /*对比*/ for(int i = 0; i < len; ++i ){ cout << &v1[ i ] << " " << &v2[ i ] << endl; } } int main() { Vector v1( 4 ); bad_copy( v1 ); return 0; }