类和对象

一、抽象和类

1、抽象

        从具体事物抽取共同的本质特征

2、C++中的类

        1.类是一种将抽象转换为用户定义类型的工具
        2.将数据表示和操纵数据的方法组合成一个整体
        3.类的实例称为对象
        4.类中的变量和函数称为成员

类是一个概念性的东西,而对象是一个实体(看得见摸得着)
类的实例称为对象,而对象的集合称之为类。类又是对象的模版

在这里插入图片描述
在这里插入图片描述

2.1类的声明

使用class/struct关键字声明类型

class 类名{};
//或者
struct 类名{};

注意
    1.class方式声明的类型与struct声明的类型仅仅是形式上不同。
    2.其唯一区别在于使用class声明的类型默认成员是私有的(private),而struct声明的类型迷人成员是公有的(public)

3.类的写法

在这里插入图片描述

写法一

LandOwner_V1.hpp创建class文件时不勾选生成 .cpp

#include <iostream>

/**
*   .hpp文件一般包含实现的内联函数,通常用于模板类这种声明与实现共存的情况
*   建议:只要不是纯模版,一律使用.h文件作为头文件后缀,使用.cpp文件作为函数的实现文件
*/
using namespace std;

class LandOwner_V1  // 棋牌游戏 地主类
{
    //private 对象的私有成员不能在外部直接使用
    private:
        string name;    //地主的名称
        long score;     //地主的得分
        int cards[20];    //地主的手牌数组

    public:
        LandOwner_V1() {}   //实现了默认构造函数
        ~LandOwner_V1() {}  //
        void TouchCard(int cardCount){//成员函数在定义时写实现函数,写不写inline关键字都是内联函数。(此时也是内联函数)
            //暂时省略函数的实现
            cout<<"开始摸:"<<cardCount<<"张牌"<<endl;
        }
        void ShowScore(){
            cout<<name<<"当前积分为:"<<score<<endl;
        }
};

main.cpp

#include <iostream>
#include "LandOwner_V1.hpp"//如果要使用类,必须包含类的头文件
using namespace std;

int main()
{
    cout << "类和对象" << endl<<endl;
    LandOwner_V1 landOwner1;    //声明(定义)一个LandOwner_V1类型的变量landOwner1
    //调用对象的成员方法
    landOwner1.TouchCard(10);

    return 0;
}

写法二

LandOwner_V2.h创建class文件时勾选生成 .cpp

#include <iostream>

using namespace std;

class LandOwner_V2
{
    private:
        string name;    //地主的名称
        long score;     //地主的得分
        int cards[20];    //地主的手牌数组

    public:
        LandOwner_V2(); //构造函数的声明
        virtual ~LandOwner_V2();//析构函数的声明

        void TouchCard(int);  //声明摸牌的方法
        void ShowScore();       //声明显示积分方法
        //短的实现可在这里,长的实现放在LandOwner_V2.cpp中
};

LandOwner_V2.cpp

#include "LandOwner_V2.h"

LandOwner_V2::LandOwner_V2()
{
    //ctor
}

LandOwner_V2::~LandOwner_V2()
{
    //dtor
}

// :: 域运算符,表示从属关系
void LandOwner_V2::TouchCard(int cardCount){
    cout<<"开始摸:"<<cardCount<<"张牌"<<endl;
}

void LandOwner_V2::ShowScore(){
    cout<<name<<"当前积分为:"<<score<<endl;
}

main.cpp

#include <iostream>
#include "LandOwner_V2.h"//不需要引入LandOwner_V2.cpp
using namespace std;

int main()
{
    cout << "类和对象2" << endl<<endl;
    LandOwner_V2 landOwner2;    //声明(定义)一个LandOwner_V1类型的变量landOwner1
    //调用对象的成员方法
    landOwner2.TouchCard(10);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值