Chinaunix首页 | 论坛 | 博客
  • 博客访问: 532736
  • 博文数量: 104
  • 博客积分: 2089
  • 博客等级: 大尉
  • 技术积分: 1691
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-29 08:48
文章分类

全部博文(104)

文章存档

2015年(1)

2013年(13)

2012年(31)

2011年(59)

分类: C/C++

2012-05-07 10:23:18

基本上和C的是一样的,只不过C++的方法要在类中声明。看一个简单实例。
ainimal.h  类里面对外公开的信息。

点击(此处)折叠或打开

  1. #ifndef _ANIMAL_H__
  2. #define _ANIMAL_H__
  3. #include <iostream>

  4. using namespace std;
  5. class Animal{

  6.         private:
  7.                 string name;
  8.         public:
  9.         void print(void);
  10.         Animal(string name){this->name=name;}

  11. };

  12. #endif


animal.cpp 类中方法实现的具体细节,或者是隐藏的部分,我新增了一个本文件私有的函数extra_info,static 修饰。

点击(此处)折叠或打开

  1. #include "animal.h"


  2. static string extra_info(){
  3.         return "Adding info from extra_info";

  4. }

  5. void Animal:: print(void){
  6.         cout << name << endl;
  7.         cout << extra_info() << endl;
  8. }


main.cpp 当然是这个类的使用者。

点击(此处)折叠或打开

  1. #include "animal.h"

  2. int main(void){

  3.         Animal ani("any");
  4.         ani.print();
  5.         cout << "some " << endl;

  6. }

编译

点击(此处)折叠或打开

  1. g++ animal.cpp main.cpp
运行

点击(此处)折叠或打开

  1. ./a.out
输出

点击(此处)折叠或打开

  1. any
  2. Adding info from extra_info
  3. some

好了,三个文件,一个类的头,一个类的实现,一个使用者
good luck


阅读(1031) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

☆彼岸★花开2012-05-08 19:26:51

不错,比较简单但是很重要的说