C++的类分为两部分: .hpp 和 .cpp
创建一个类:man,man的实例对象包含两个属性变量:name 和 age
一..hpp文件
#ifndef man_hpp
#define man_hpp
#include <stdio.h>
class man{
//在类的内部没有权限限定符,默认是private
//在结构内部没有权限限定符,默认是public
private:
//定义成员变量
char name[100];
int age;
public:
//构造函数,如果不写构造函数,系统内部会自动生成一个构造函数
man();
//析构函数
~man();
//设置方法
void set_name(const char *s);
void set_age(int i);
//获取方法
const char *get_name();
int get_age();
};
#endif /* man_hpp */
二..hpp文件
#include <iostream>
#include "man.hpp"
#include "man.hpp"
#include <string.h>
//命名空间
using namespace std;
//一个类实例化一个对象的时候自动调用构造函数
man :: man(){
cout << "man" << "\n";
//初始化name
memset(name, 0, sizeof(name));
//初始化age
age = 0;
}
//当对象在内存中销毁的时候自动被调用
man::~man(){
cout << "~man" << "\n";
}
//::调用设置方法
void man::set_name(const char *s){
strcpy(name, s);
}
void man::set_age(int i){
age = i;
}
//调用获取方法
const char *man::get_name(){
return name;
}
int man::get_age(){
return age;
}
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "man.hpp"
//命名空间
using namespace std;
int main(int argc,const char * argv[]) {
std::cout <<"Hello, World!\n";
man m;
m.set_name("tiantian");
m.set_age(10);
cout <<"name =" << m.get_name() <<"\n";
cout <<"age = " << m.get_name() <<"\n";
return 0;
}