10.5 合理使用类(内联函数)

Posted: March 27, 2011 in C++

ClassUsing.h :

/*
大多数程序员使用的方法是将类放入头文件里.该头文件的扩展名为.h,.hp, .hpp.

例如,将Cat类的声明放在一个名为Cat.h的文件中, 而将类方法的定义放在Cat.cpp文件中.
然后,在Cat.cpp将其关联,开头加入如下代码:

#include “Cat.h” //就好像输入了该文件内容一样

那为什么要将它们分开? 大多数情况下,类的客户并不关心实现细节.
只要阅读头文件,就可以知道需要的信息了,他们可以忽略实现文件.

之前说过 内联函数 ,类方法也可以作为内联的.只需要在返回类型前加上关键字inline.
例如, GetAge()函数的内联如下:

inline int Cat::GetWeight()
{
         return itsWeight;
}

也可以将函数的定义放到类生命中,这样函数将自动成为内联的.
例如:

class Cat
{
public:
         void SetWeight(int Weight);
         int GetWeight(){return itsWeight;} //inline
};

也可以这样写:

class Cat
{
public:
         void SetWeight(int Weight);

         int GetWeight() const  //inline
         {
                  return itsWeight;
         }
};

*/

class Cat
{
private:
         int itsAge;

public:
         void SetAge(int age){itsAge=age;}
         int GetAge(){return itsAge;} //inline
};

====================================

Cat.cpp :

/*实现文件*/
#include “ClassUsing.h”
#include <iostream>

using namespace std;

void main()
{
         Cat Frisky;
         Frisky.SetAge(5);
         cout<<“Cat is “<<Frisky.GetAge()<<” years old.”<<endl;
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s