其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·前两天看到的#pragma用法
·用C写的简单学生成绩管理系统
·射频芯片nRF401天线设计的分析
·入门系列--OpenGL最简单的入门
·简单的CreateRemoteThread例程-初学者必看
·BCB数据库图像保存技术
·GNU中的Makefile
·使用AutoMake轻松生成Makefile
·数据结构

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
C++ 初始化和赋值的不同

作者:未知 来源:月光软件站 加入时间:2005-5-13 月光软件站

c++中初始化和赋值操作差别是很大的。

对于基本数据类型差别不大:

比如:
int a = 12; // initialization, copy 0X000C to a
a = 12; // assignment, copy 0X000C to a

但是对用户自定义的数据类型比如String 初始化和赋值就差别很大:
class String {
public:
String( const char *init ); // intentionally not explicit!
~String();
String( const String &that );
String &operator =( const String &that );
String &operator =( const char *str );
void swap( String &that );
friend const String // concatenate
operator +( const String &, const String & );
friend bool operator <( const String &, const String & );
//...
private:
String( const char *, const char * ); // computational
char *s_;
};

初始化的构造过程比较简单:先分配一个足够大的空间然后填充上数据:

String::String( const char *init ) {
if( !init ) init = "";
s_ = new char[ strlen(init)+1 ];
strcpy( s_, init );
}

析构过程更简单:
String::~String() { delete [] s_; }

但是如果赋值操作就复杂多了:

String &String::operator =( const char *str ) {
    if( !str ) str = "";
    char *tmp = strcpy( new char[ strlen(str)+1 ], str );
    delete [] s_;
     s_ = tmp;
    return *this;
}

看来在条件允许的情况下最好在初始化的时候就赋值,而尽量避免用=号赋值了。


相关链接: C++ Common Knowledge: Assignment and Initialization Are Different

其他
机器人聊天

                网摘  

                近日心情 
                   
                    爱吧

                CtrlC 源代码搜索引擎

                图片转化为字符

                百家姓,姓名查询

                唐诗、宋词、元曲 搜索引擎

                小叮咚首页  讨论






相关文章

相关软件




月光软件程序下载编程文档电脑教程网站设计网址导航网络文学游戏天地幽默笑话生活休闲写作范文安妮宝贝
电脑技术编程开发网络专区谈天说地情感世界游戏元素分类游戏热门游戏体育运动手机专区业余爱好影视沙龙
音乐天地数码广场教育园地科学大观古今纵横谈股论金人文艺术医学保健动漫图酷二手专区地方风情各行各业

月光软件站·版权所有