面对对象:将系统看成对象的集合,对象之间通过交互作用来完成系统特定功能;
面对对象编程的特点:继承、封装、多态;
进入主题:
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();
类外实现成员函数: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;私有成员,必须通过成员函数来进行访问
t2.x_=5;
t2.initXYZ(6,7,8);
cout<<sizeof(t1)<<endl;
cout<<sizeof(t2)<<endl;
system("pause");
return 0;
}
输出结构一致,都为12;对象大小与成员函数无关,只与成员变量有关;
当加入一个char成员时,结果变为16,类遵循字对齐
4.对象的存储模型
this 指针的作用:成员方法是共享的,怎么辨别是哪个对象调用的方法?
this指针保存调用方法对象的地址
5.类的作用域
前项声明:可以只声明而不定义它。这个声明有时被称为前向声明。在声明之后,定义之前,类是一个不完全类型,即只知是一个类,但不知道类中具体包含哪些成员。不完全类型只能以有限方式使用,不能实例化,只能用于定义指向该类型的指针及引用,或者用于声明使用该类型作为形参类型或者返回类型的函数。
class A;
class B{
public:
A* m_a;//不能用A m_a
}
#include "A.h"
class B{
public:
A* m_a;//(或者A m_a)
}
前向声明的好处是:
不必要的#include 会增加编译时间.
混乱随意的#include可能导致循环#include,可能编译错误;
6.嵌套和局部类
从作用域看,嵌套类被隐藏在外围类之中,只能在外围类中使用。如果在外围类的作用域使用时,需要加名字限定。
嵌套类中的成员函数可以在它的类体外定义
嵌套类的成员函数对外围类没有访问权,反之亦然
嵌套类仅仅是语法上的嵌入
demo4.c
#include<iostream>
using namespace std;
class Test{
public:
int x_;
class Inner{
public:
int num;
void func()
};
};
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();//访问嵌套类的成员方法
return 0;
}
7.局部类
定义在函数体内的类为局部类,只在定义它的局部域可见。局部类的成员函数不惜被定义在类体中。
局部类中不能有静态成员。