【Effective C++】学习之一:声明、定义、初始化、赋值

1.声明(declaration)

用来将一个object、function、class、或者template的型别名称告诉编译器,声明是不带有细节信息。比如:

extern int x;               //object declaration
int numDigits(int number);  //function declaraton
class Clock;                //class declaration      //这些均是声明
template<class T>
class SmartPointer;         //template declaration

2.定义(definition)

将细节信息提供给编译器。对object来说,其定义就是编译器为它分配内存地址。对function或function template来说其定义就是提供函数本体(function body)。对class或class template来说,其定义式必须列出该class或template的所有members;

int x;                      //这是对象的定义式
int numDigits(int number)   //函数的定义式
{ 
  ......                   //函数的实现
}

class Clock               //类Clock的定义
{
public :
 Clock();
 ~Clock();
 int hour() const;
 int minute() const;
 int second() const;
 ...
};

template<class T>       //template的定义式
class SmartPointer
{
 public:
 SmartPointer();
 ~SmartPointer();
 T* operator->() const;
 T& operator*() const;
 ...
};

3初始化(initialization)与赋值(assignment)

对象的初始化行为发生在它初次获得一个值的时候。对于“带有constructor”的class或struct,初始化总是经由调用某个constructor达成。
对象的赋值发生在“已初始化之对象被赋值新值”。如:

string s1;                   //初始化
string s2("hello world");    //初始化
string s3=s2;                //初始化
s1=s2;                       //赋值

初始化操作是由constructor执行,赋值由operator=执行。这两个动作对应不同的函数操作。

猜你喜欢

转载自blog.csdn.net/wu_qz/article/details/80112349