面对对象:面对将系统看成通过交互作用来完成特定功能的对象的集合。每个对象用自己的方法来管理数据。也就是说对象内部的代码能够操作对象内部的数据。
特点:(抽象)——灵活性
继承—— 复用性
封装—— 维护性
多态—— 扩展性
类
1. 类的声明
class 类名称
{
public:
公有成员(外部接口)
private:
私有成员 (只允许本类中的函数访问,而类外部的任何函数都不能访问)
protected:
保护成员(与private类似,差别表现在继承与派生时)
};
2. 成员函数
demo1.cpp:
#include <iostream>
using namespace std;
class Test
{
public:
int x_;
void init(int x, int y,int z);
void display()
{
cout<< x_ << endl;
};
private:
int y_;
protected:
int z_;
};
void Test::init(int x, int y, int z)
{
x_ = x;
y_ = y;
z_ = z;
}
int main()
{
Test t;
t.init(1,2,3);
t.display();
return 0;
}
类内实现成员函数(默认为内联函数) :display()
(http://blog.csdn.net/wangfei8348/article/details/51385203)
类外实现成员函数:Test::init()
标准写法:
Test.h —— 放类的声明
Test.cpp —— 放成员函数的定义 (成员函数可重载)
Main.cpp—— 主函数
3. class VS struct
class数据成员默认私有
struct数据成员默认公有
demo2.cpp
#include <iostream>
using namespace std;
class Test
{
int x_;
int y_;
int z_;
};
struct Test1
{
int x_;
int y_;
int z_;
void initXYZ(int x, int y, int z)
{
x_ = x;
y_ = y;
z_ = z;
}
};
int main()
{
Test t1;
Test1 t2;
//t1.x_ = 5;class数据成员默认私有,不能被直接访问
t2.x_ = 5;//struct数据成员默认公有 此写法是C++对struct的升级
t2.initXYZ(6,7,8);
cout<< sizeof(t1) <<endl;
cout<< sizeof(t2) <<endl;
return 0;
}
结果:
当类中加入一个成员函数时,结果不变,对象大小与成员函数无关,至于成员有关
当当类中加入一个char 成员时,结果变为16,类遵循字对齐
4. 对象的存储模型
this指针的作用<——成员方法是共享的,怎么辨别哪个对象调用的方法?
this指针保存调用方法对象的地址
5. 类的作用域
前向声明 (前向声明的类不能实例化) 注:用类创建对象的过程称做实例化
前向声明不可以在一个类里定义另一个类的对象,只能定义对象的指针或引用
(demo3.c)http://liam2199.blog.51cto.com/2879872/1172175
6. 嵌套类
从作用域看,嵌套类被隐藏在外围类之中,只能在外围类中使用。如果在外围类的作用域使用时,需要加名字限定。
嵌套类中的成员函数可以在它的类体外定义
嵌套类的成员函数对外围类没有访问权,反之亦然
嵌套类仅仅只是语法上的嵌入
demo4.c
#include <iostream>
using namespacestd;
class Test
{
public:
intx_;
classInner
{
public:
intnum;
voidfunc();
};
};
void Test::Inner::func()
{
cout<<"hello world!"<<endl;
}
int main()
{
class LocalClass //局部类
{
void func()
{
}
};
Test t;
Test::Inner n; //定义嵌套类对象
t.x_ = 1;
cout<< t.x_ <<endl;
n.num = 2; //访问嵌套类的成员
cout<< n.num <<endl;
n.func ();//访问嵌套类的成员方法
return0;
}
7. 局部类
定义在函数体内的类为局部类(loacl class),只在定义它的局部域可见。局部类的成员函数不惜被定义在类体中。
局部类中不能有静态成员。