2016年06月15日学习日记 c++第一讲
1、两种编程思想:
面向对象:将问题分解成各个对象,从而对它的属性和行为以及对象间的关系进行分析。对象举例(人或者各种实物) ;代表语言:C++、java、C#
组成:属性:静态特征、行为:动态特征
例:人:[姓名、性别、年龄]、[吃饭、睡觉、打豆豆]
长方形:[长、宽]、[计算面积、计算周长、放大、旋转]
长方体:[长、宽、高]、[体积]
类 对象:类是对象的一个类型 int a,float b
对象就是一个变量
面向过程:自上而下的设计方式,步骤:(获得数据,对数据进行处理,得到结果)代表语言:C
区别:面向过程编程是一种直接的编程方法,按照编程语言的思路考虑
面向对象是一种抽象度跟高的编程方法,目标的使模块的抽象度更高,可复用行更好
2、类和对象:类是对象的(抽象)类型(类:具有相同属性和行为的一组对象的抽象)
对象是类的具体实例,类是对像的变量(一定程度上对象就是一个变量)
3、面向对象的三大特征:封装、继承、多态
封装:把数据和操作组成到一起(将所有的事物抽象成一个概念,然后进行使用)
继承:提高代码复用性
多态:通过一个指针来统一管理子量
4、类的创建: class :用于创建类型的关键字 class 类名
属性(一般为私有,安全):private
行为(一般为公有,便于继承):public
定义类时,类名首字母一般大写
定义函数一般第一个单词小写第二个单词首字母大写
#ifndef Circle_hpp
#define Circle_hpp
….//防止头文件重复包含
#endif
构造函数:给对象赋初值,在创建对象时自动被调用(开辟空间 初始化)
1):创建对象时,有几个实參,那么就自动调用带有几个形參的构造函数
2):当程序中没有任何构造函数,编译器自动提供一个没有参数的构造函数(如果自定义任何一个构造函数,编译器不再提供该默认的无參构造函数)
3):默认构造函数:不传递任何参数就被调用的构造函数被称为默认构造函数
4):标准非默认构造函数被调用时,实參个数与形參个数必须相同
特征:
1):类中构造函数的访问权限必须为公有(public);
2):构造函数名和类名相同;
3):构造函数没有返回值;
4):构造函数可以带参数;
类占用存储空间大小:
结构体与类:
结构体:所有元素累加(最大值上下分别补齐)
类:‘属性’(和行为‘无关’)所有属性累加补齐(最大值上下分别补齐)(与行为无关)(空类占用空间为1)
课堂练习:
Cube.cpp:
#include "Cube.hpp"
#include <iostream>
using namespace std;
Cube::Cube()
{
length=1;
width=1;
hight=1;
}
Cube::Cube(float l)
{
length=l;
width=1;
hight=1;
}
Cube::Cube(float l,float w)
{
length=l;
width=w;
hight=1;
}
Cube::Cube(float l,float w, float h)
{
length=l;
width=w;
hight=h;
}
void Cube::setLength(float l)
{
length=l;
}
void Cube::setWidth(float w)
{
width=w;
}
void Cube::setHight(float h)
{
hight=h;
}
float Cube::getLength()
{
return length;
}
float Cube::getWidth()
{
return width;
}
float Cube::getHight()
{
return hight;
}
float Cube::getVolume()
{
return length*width*hight;
}
float Cube::getVolumSum(Cube c1,Cube c2)
{
return getVolume()*c1.getVolume()*c2.getVolume();
}
void Cube::print()
{
cout<<"length:"<<length<<endl;
cout<<"width:"<<width<<endl;
cout<<"hight:"<<hight<<endl;
cout<<"volume:"<<getVolume()<<endl;
}
Cube.hp:
#ifndef Cube_hpp
#define Cube_hpp
#include <stdio.h>
class Cube
{
private:
float length;
float width;
float hight;
public:
Cube();
Cube(float l);
Cube(float l,float w);
Cube(float l,float w, float h);
void setLength(float l);
void setWidth(float w);
void setHight(float h);
float getLength();
float getWidth();
float getHight();
float getVolume();
void print();
float getVolumSum(Cube c1,Cube c2);
};
#endif /* Cube_hpp */
main.cpp:
#include <iostream>
#include "Cube.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
Cube c1,c2(1,1),c3(1,1,3);
c1.setLength(1);
c1.setWidth(1);
c1.setHight(2);
cout<<"length:"<<c1.getLength()<<endl;
cout<<"width:"<<c1.getWidth()<<endl;
cout<<"hight:"<<c1.getHight()<<endl;
cout<<"volume:"<<c1.getVolume()<<endl;
cout<<"using print function:"<<endl;
c1.print();
c2.print();
c3.print();
cout<<c3.getVolumSum(c1, c2)<<endl;
return 0;
}