目录
一、从C到C++
1.识别结构
- #include<iotream>
#include是指包含后面所跟的内容,
iostream是input output stream的缩写,意思是输入输出流。
所以#include<iotream>定义的就是你要输入和输出的内容。
2.引用
int n=4;
int & r=n;//r引用了n,r的类型是int &
对某个变量的引用,等价于这个变量,相当于该变量的一个别名。
double a = 4, b = 5;
double & r1 = a;
double & r2 = r1;
r2 = 10;
cout << a <<endl;
r1 = b;
cout << a << endl;
输出
2.1高级引用
int n = 4;
int & SetValue() { return n; } //函数名,参数为空,返回n
int main()
{
SetValue() = 40;
cout << n;
return 0;
}
2.2常引用
加上const
const int &r2 = r;
注:不能通过常引用修改引用值
3.指针
使用指针时会频繁进行以下几个操作:定义一个指针变量、把变量地址赋值给指针、访问指针变量中可用地址的值。
3.1通过指针传参
下面举个例子来说明通过指针传递参数给变量var
#include <iostream>
using namespace std;
int main ()
{
int var = 20; // 实际变量的声明
int *ip; // 指针变量的声明
ip = &var; // 在指针变量中存储 var 的地址
*ip = 6 ;
cout<<"var="<<var<<endl;
return 0;
}
通过赋值指针*ip,将var的值由20变为6:
3.2
二.面向对象的程序设计
面向对象的程序设计具有“抽象”,“封装”,“继承”,“多态”四个基本特点
面向对象的程序设计有比面向过程有一个好处,就是类中的定义不必担心与其他类因重名产生冲突。这跟“游戏中的开疾跑对所有英雄的效果是一样的”是一个概念。
举个例子
class Box
{
public:
double length; // 盒子的长度
double breadth; // 盒子的宽度
double height; // 盒子的高度
};
关键字public确定了类成员的访问属性
1.访问数据成员
可直接使用“.”来访问
实例
#include <iostream>
using namespace std;
class Box
{
public:
double length; // 长度
double breadth; // 宽度
double height; // 高度
// 成员函数声明
double get(void);
void set( double len, double bre, double hei );
};
// 成员函数定义
double Box::get(void)
{
return length * breadth * height;
}
void Box::set( double len, double bre, double hei)
{
length = len;
breadth = bre;
height = hei;
}
int main( )
{
Box Box1; // 声明 Box1,类型为 Box
Box Box2; // 声明 Box2,类型为 Box
Box Box3; // 声明 Box3,类型为 Box
double volume = 0.0; // 用于存储体积
// box 1 详述
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 详述
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// box 1 的体积
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Box1 的体积:" << volume <<endl;
// box 2 的体积
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Box2 的体积:" << volume <<endl;
// box 3 详述
Box3.set(16.0, 8.0, 12.0);
volume = Box3.get();
cout << "Box3 的体积:" << volume <<endl;
return 0;
}