面向对象
所谓面向对象就是基于对象概念,以对象为中心,以类和继承为构造机制,来认识、理解、刻画客观世界和设计、构建相应软件系统(模拟现实)
1、对象是由数据和容许操作组成的封装体,与客观世界有直接对应关系;
2、面向对象不是某一种语言特有,而是一种编程思想;
抽象
从具体事务提取出的共同特征
类
1、类是一种将抽象转换为用户定义类型的工具
2、将数据表示和操作数据的方法组合成一个整体
3、类的实例成为对象
4、类中的变量和函数称为成员
如:
地主类
成员变量:名称、积分、手牌
成员函数:摸排、出牌、查看积分
/**
*地主类的声明
*/
class LandOwer {
public:
LandOwer(); /** 默认构造函数 */
~LandOwer(); /** 默认构析函数 */
string name; /** 名称 */
long score; /** 积分 */
int cards[20]; /** 手牌数组 */
void Touchcard(int[]); /** 摸牌 */
bool Playcard(int[]); /** 出牌 */
void Showscore(); /** 查看积分 */
};
类的声明
1、使用class struct声明类
class 类名{}; //class Landower{};
struct 类名{}; //struct Landower{};
注意:
1、class方式声明的类型与struct声明仅仅是形式上的不同;
2、其位唯一的区别在于使用class声明的类型默认成员是私有的(private),而
struct声明的类型默认成员公有的(public)
具体代码
类.h文件代码
#pragma once
#include<iostream>
#include<string>
using namespace std;
// .hpp文件通常用于模板类,通常用于模板类这种声明与实现共存的情况
/**
*地主类的声明
*/
class LandOwer {
private:
string name; /** 地主名称 */
long score; /** 积分 */
int cards[20]; /** 手牌数组 */
public:
LandOwer(); /** 默认构造函数 */
~LandOwer(); /** 默认构析函数 */
void Touchcard(int Cardcount) {//在类添加函数,直接人为是内联函数(inline void Touchcard)
/** 摸牌 */
cout << name << "摸牌" << Cardcount << "张牌" << endl;
}
bool Playcard(int[]); /** 出牌 */
void Showscore() { /** 查看积分 */
cout << name << "当前积分为:" << score << endl;
}
};
main函数:
#include<iostream>
#include<string>
#include"类.h"
using namespace std;
int main ()
{
**LandOwer landower1;//定义了一个 LandOwer类型的变量landower1
//调用变量的方法**
landower1.Touchcard(100); //不可以对private变量进行操作,只可以操作public变量
return 0;
}
输出:摸了100张牌
类的创建方法
创建.h文件和.cpp文件
.h文件功能:声明函数,如果太长则不进行具体的函数运算
.cpp文件功能:实现对应.h文件要实现的函数声明
类的总结
https://www.cnblogs.com/weekbo/p/8184141.html
补充
1、
solution.h文件:
#pragma once
#include<iostream>
#include<string>
using namespace std;
class Landower
{
public://可以写函数和声明
string name;
void ame(string);
};
void Landower::ame(string na)
{
cout << na << "是谁" << endl;
};
main.cpp:
#include<iostream>
#include<string>
#include"solution.h"
using namespace std;
int main()
{
string na = "xka";
Landower Land;
Land.ame(na);
return 0;
}
1)对于.h文件中类里面函数的调用方式要注意;
2)对于“::”,表示作用域解析运算符,表示作用域和所属关系;
2、