第六章 面向对象面向对象程序设计

什么是面向对象程序语言

这里写图片描述
这里写图片描述
这里写图片描述

面向对象语言的主要特征

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

什么是类,对象和成员

这里写图片描述
这里写图片描述
这里写图片描述

声明一个类

#include<iostream>
using namespace std;

//声明一个类 
class Human
{
    public:
        void GetStature();
        void GetWeight();
    private:
        int stature;
        int weight;
};

int main()
{

} 

这里写图片描述

#include<iostream>
using namespace std;

//声明一个类 
class Human
{
    public:
        void GetStature()
        {
            cout<<stature;
        }
        void SetStature(int x)
        {
            stature=x;
        }
        void GetWeight();
        void SetWeight(int x);
    private:
        int stature;
        int weight;
};

void Human::GetWeight()
{
    cout<<weight;
}
void Human::SetWeight(int x)
{
    weight=x;
}

int main()
{
    Human Mike;
    Mike.SetStature(8);
    cout<<"麦克的身高";
    Mike.GetStature();
    cout<<endl;
    Mike.SetWeight(80);
    cout<<"麦克的体重";
    Mike.GetWeight();
} 

这里写图片描述

公有和私有

#include<iostream>
using namespace std;

class Human
{
    public:
        void set(int w)
        {
            if(w>0&&w<100)
            {
                weight=w;
            }
            else
            {
                cout<<"请将set函数设置为一个大于0而小于100的数字,否则默认返回0"<<endl; 
                weight=0;           
            }
        }
        int show()
        {
            return weight;
        }
    private:
        int weight;
};

int main()
{
    Human Tom;
    Tom.set(90);
    cout<<"汤姆的体重为: "<<Tom.show()<<"\n";
    Human Mike;
    Mike.set(80);
    cout<<"迈克的体重为: "<<Mike.show()<<"\n";
    return 0;
}

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

内联函数

#include<iostream>
using namespace std;

class A
{
    public:
        inline void print(int);
        int get()
        {
            return x;
        }
    private:
        int x;
};

//inline int print(int);//声明内联函数
void A::print(int a) 
{
    x=a;
}

int main()
{
    A a;
    int x;
    cout<<"请输入一个数字\n";
    cin>>x;
    a.print(x);
    cout<<"\n";
    cout<<"输入的数字为: "<<a.get()<<endl; 
    return 0;
}

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

析构函数

这里写图片描述

#include<iostream>
using namespace std;

class A
{
    public:
        A();
        ~A();
        //构造函数 
        /*A()
        {
            cout<<"构造函数执行完毕!\n";
        }*/
        //析构函数 一个类只能有一个析构函数 
        /*~A()//析构函数不能有参数,无返回值 
        {
            cout<<"析构函数执行完毕!\n";
        }*/
};

A::A()
{
    cout<<"构造函数执行完毕!\n";
}
A::~A()
{
    cout<<"析构函数执行完毕!\n";
}

int main()
{
    A a;
    return 0;
} 

这里写图片描述
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值