千里之行,始于足下

《effetive c++》学习笔记 Introduction

 

Introduction
1)declarations and definition
         

extern int x;                          // object declaration
int x;                                 // object definition


2)默认构造函数,要么没有参数,要么制定参数的初始值,否则定义类的数组的时候会出错。

class A ;
A arrayA[
10];                            // 10 constructors called

class B ;

B arrayB[
10];                            // 10 constructors called,
                                         
// each with an arg of 0
class C ;
C arrayC[
10];                            // error!


对无法直接声明为数组对象的类,则需要使用指针数组。

*ptrArray[10];                          // no constructors called

ptrArray[
0= new C(22);                  // allocate and construct
                                          
// 1 C object
ptrArray[1= new C(4);                   // ditto


3)copy constructor 主要用于值传递的类
   

class String ;
String s1;                                 
// call default constructor
String s2(s1);                             // call copy constructor
String s3 = s2;                            // call copy constructor


4)initialization 与 assignment

string s1;                                // initialization
string s2("Hello");                       // initialization
string s3 = s2;                           // initialization
s1 = s3;                                  // assignment


前者是在构造函数中,后者是利用赋值操作符”=”,实际就是调用的函数不同。前者注重数据的合法性,而后者注重数据内存的管理。

// a possible String constructor
String::String(const char *value)
{
  
if (value) {                            // if value ptr isn't null
    data = new char[strlen(value) + 1];
    strcpy(data,value);
  }

  
else {                                  // handle null value ptr3
  
    data 
= new char[1];
    
*data = '\0';                         // add trailing null char
  }

}

// a possible String assignment operator
String& String::operator=(const String& rhs)
{
  
if (this == &rhs)
    
return *this;                          // see Item 17

  delete [] data;                          
// delete old memory
  data =                                   // allocate new memory
    new char[strlen(rhs.data) + 1];
  strcpy(data, rhs.data);

  
return *this;                            // see Item 15
}


 
5)几种表达方式
1,const_cast is designed to cast away the constness of objects and pointers, a topic I examine in Item 21.
2,dynamic_cast is used to perform "safe downcasting," a subject we'll explore in Item 39.
3,reinterpret_cast is engineered for casts that yield implementation-dependent results, e.g., casting between function pointer types. (You're not likely to need reinterpret_cast very often. I don't use it at all in this book.)
4,static_cast is sort of the catch-all cast. It's what you use when none of the other casts is appropriate. It's the closest in meaning to the conventional C-style casts.

 

posted on 2007-12-06 16:58 rednight 阅读(219) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理