14:类初步使用

来源:互联网 发布:北部战区山东知乎 编辑:程序博客网 时间:2024/05/16 15:31
#include <iostream>
using namespace std;

struct cat
{
double 体重;
double 身高;
};

//c语言里有struct
//c++继承了c语言的struct
//struct变成了class,两者都可继承,几乎完全一样
//唯一区别:struct默认访问public,class默认private
class dog
{
private:
//默认访问控制为private
double 体重;
double 身高;

};//注意分号

class 学生
{
//类成员
//数据成员
//成员函数
//公有,私有
};

//销售项,就是销售的一本书
class sale_item
{
public:
//类的操作:成员函数
private:
string isbn; //书号
unsigned units_sold;//销售数量
double revenue;//金额
};

int main()
{
dog a;
学生 b;

///////////////
system("pause");
return 0;
}

1,类
2,从操作开始设计类
接口
实现

3,使用struct关键字


/////////////////////////////////////////////

//编写自己的头文件

//demo.h
//类的定义
//外部变量的声明
//函数的声明
//只能写声明,不能写定义

//解决多重包含:头文件保护符
#ifndef _DEMO_H  //变量
#define _DEMO_H

double rate;//error
int a;//error

extern double rate;
extern int a;
extern int a = 10;//error

//const常量的定义可以写在头文件
const int b = 99;

class demo
{
};
#endif


//demo.cpp
#include "demo.h"
//类的定义,类的所有的成员



#include <iostream>//标准头文件
#include <string>

#include "demo.h"//自定义头文件

using std::cout;
using std::string;

int main()
{
system("pause");
return 0;
}

1,使用多个文件编写程序
多个头文件
多个源文件
2,设计自己的头文件
头文件用于声明,不是用于定义
一些const对象可以定义在头文件里
3,预处理器简介
头文件包含头文件
避免多重包含
使用自定义的头文件

//编辑-->预处理-->编译-->链接-->执行/运行

//预处理:替换头文件,把头文件里内容全部拷贝过来
//头文件包含头文件,导致多重包含,多次拷贝
//解决多重包含:头文件保护符
#ifndef _DEMO_H
#define _DEMO_H
//类的声明
class dog
{
};
#endif

0 0