类中赋值函数注意事项

来源:互联网 发布:sql server使用 编辑:程序博客网 时间:2024/06/05 00:28

 

转载请标明是引用于 http://blog.csdn.net/chenyujing1234 

欢迎大家拍砖

 

#include <stdlib.h>#include <stdio.h>class CTest{public:CTest() : m_value(100){}public:CTest & operator=(const CTest &cTestSource){printf("Enter CTest & operator=(const CTest &cTestSource)\n");m_value = cTestSource.m_value;return *this;}CTest * operator=(const CTest *cTestSource){printf("Enter CTest * operator=(const CTest *cTestSource)\n");m_value = cTestSource->m_value;return this;}public:int m_value;};int main(){CTest *pCTest = NULL;int *pInt = NULL;CTest cTest;// 这样pCTest一直为NULL//pCTest[0] = (CTest*)&cTest;//pCTest[1] = (CTest*)&cTest;// 这样pCTest可以得到地址值,但没有进入任何的赋值函数中pCTest = (CTest*)&cTest;// 没有报错,会进入函数CTest * operator=(const CTest *cTestSource)pCTest[1] = (CTest*)&cTest;// 会报错,会进入函数CTest & operator=(const CTest &cTestSource)// 报错地方:m_value = cTestSource.m_value;(这是因为此时pCTest[1]在内存中没有,所以访问值时出现报错)pCTest[1] = cTest;// pCTest[1]的地址为NULL,所以下面的调用是报错的  printf("m_value is %d\n", pCTest[1].m_value);system("pause");return 0;}


 

原创粉丝点击