面向对象编程(一)

面向对象编程介绍

1.什么是面向对象
面向将系统看成通过交互作用来万恒特定功能的对象的集合。每个对象用自己的方法来管理数据。也就是说只有对象内部的代码能够操作对象内部的数据
2.面向对象的优点
通过,继承、封装、多态降低程序的耦合度,并结合设计模式让程序更容易修改和扩展,并且易于复用。
3.面向对象的特点

① 封装——维护性
② 继承——复用性
③ 多态——扩展性
④ 抽象

类与对象

1.类的声明

class Test
{
public:
    公有成员(外部接口):对外可以访问
private:
    私有成员:不能在类外访问
protect:
    保护成员:不能在类外访问
};

2.成员函数
类内实现的方法默认为inline函数
Test.h

#ifndef _TEST_H_
#define _TEST_H_

class Test
{
pubilc:
int x_;
void initXYZ(int x, int y, int z);
void displayXYZ();
protected:
    int y_;
private:
    int z_;
};

Test.cpp

#include “Test.h”
#include <iostream>

void Teat::initXYZ(int x, int y, int z)
{
x_=x;
y_=y;
z_=z;
}
void Test:display()
{
    cout x_<<”\ny_”<<”\nz_”<<endl;
}

Main.cpp

#include <iostream>
#include “Test.h”
int main()
{
Test t;
t.x_ = 5;

t.initXYZ(1,2,3);
t.displayXYZ();

    return 0;
}

3.class VS struct
class数据成员默认私有
struct数据成员默认公有
class与struct一样遵循字对齐,大小只与成员有关,方法是共享在同一段空间中
4.对象的存储模型
this指针自动传参

Test *t1 = new Test();
t1->initXYZ(1,2,3);

调用时自动传输this指针,保存对象的地址
5.类的作用域
在A.h中调用B的类:
① 可用#include “B.h”
② 可以前向声明

A.h

#ifndef _A_H_
#define _A_H_

//#include "B.h"

class B;

class A
{
public:
    A();
    ~A();
private:
    B *b;
};

#endif

6.嵌套类(内部类)

class A
{
public:
int x_;
class Inner:
{
public:
    int num;
    func;
};
};

7.局部类

class LoclClass
{
func()
{
...........
}
};

局部类只在定义它的局部域内可见。
局部类的成员函数必须被定义在类体中
局部类中不能有静态成员

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值