【c++思维导图与代码示例】05 数组、指针、字符串

【c++思维导图与代码示例】05 数组、指针、字符串

思维导图:

在这里插入图片描述

代码示例:

  • 示例1:

/*************************************************
**
**Description: 简单的一维数组示例 
**
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-1.cpp
** 
*
***************************************************/

#include <iostream>
using namespace std;
int main(){
    int a[10],b[10];
    for (int i=0; i<10;i++){
        a[i] = i*2-1;
        b[10-i-1] = a[i];
    }
    for (int i = 0; i<10;i++){
        cout << "a[" << i <<"] = "<<a[i]<<" ";
        cout << "b[" << i <<"] = "<<b[i]<<endl;
    }
    system("pause");
    return 0;
}

  • 示例2:

/*************************************************
**
**Description: 使用数组存放数据:斐波那契数列前50项数据
**
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-2.cpp
** 
*
***************************************************/
# include <iostream>
using namespace std;
int main(){
    int f[50]={1,1};              // 只初始化下标为 0、1 的数值
    for (int i=2;i<50;i++){      //求第2--49个数
        f[i] = f[i-2] + f[i-1];   // 数列的项规律
    }
    for (int i = 0;i<50;i++){     
        if (i%5==0) cout << endl; // 设置 每行输出 5 项
        cout.width(12);           // 设置输出项的宽度
        cout << f[i];
    }
    system("pause");
    return 0;

}

  • 示例3:

/*************************************************
*
**Description: 定义一个二维数组,表示一个矩阵,输出矩阵;然后调用子函数,
** 分别计算每一行元素的和,并将元素和直接存放在每一行的第一个元素中,
** 返回主函数之后,输出各行元素的和;了解数组名作为参数的使用
** Author:慕灵阁-wupke
** Time:2021-11-15
** Versions :5-3.cpp
** 
*
***************************************************/
#include <iostream>
using namespace std;

void rowSum(int a[][4], int nRow){ // 计算二维数组A每行元素的和
    for (int i = 0;i< nRow;i++){
        for(int j=1;j<4;j++)
        a[i][0] += a[i][j];
    }
}
//  主函数
int main(){
    int table[3][4] = {{1,2,3,4},{2,3,4,5},{3,4,5,6}};
    for(int i= 0;i<3;i++){  // 输出数组元素
        for (int j=0;j<4;j++)
        cout << table[i][j]<< "  ";
        cout  << endl;
    }
    rowSum(table,3)  ;  // 调用子函数,计算各行的和
    for (int i=0;i<3;i++){  // 输出计算结果
        cout << "Sun of row  "<< i << "  is  " << table[i][0] <<endl;   // 这样的过程中,原始数组table的元素已经被改变了(没有用const常量传递)
    }
    // 再次输出table
    for(int i= 0;i<3;i++){  // 输出数组元素
        for (int j=0;j<4;j++)
        cout << table[i][j]<< "  ";
        cout  << endl;
    system("pause");
    return  0;
    }
}

  • 示例4:

/*************************************************
*
**Description: 了解基于范围的for循环(遍历数组元素)
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-4.cpp
** 
***************************************************/

#include <iostream>
using namespace std;


int main(){
    int array[3]={1,2,3};
    for(int&e:array){
        e += 2;
        cout<<e<<endl;
    }
    system("pause");
    return 0; 
}

  • 示例5:

/*************************************************
*
**Description: 了解 指针的 声明、赋值、使用、知道指针常量、常量指针的区别
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-5.cpp
** 
***************************************************/

#include<iostream>
using namespace std;
int main(){

    int i;  // 定义 int 类型数 i 
    int *ptr = &i;  // 取i 的地址赋给 ptr
    i = 100;        // 赋值
    cout<< " i=  " << i << endl;    // 输出int 类型数的值
    cout<< " *ptr=  " << *ptr << endl;  // 输出int 类型指针所指地址的内容

    // void 类型的指针使用
    void *pv;      // 声明 void 类型的指针
    int a = 5;
    pv = &a;       // 取整型变量的地址赋给void类型指针
    int *pint = static_cast<int*>(pv);    // void 类型指针转换为 int 型指针
    cout << " *pint=  " << *pint << endl;



    // 理解常量指针与  指针常量

    // 常量指针:不能通过指向常量的指针改变所指对象的值,但指针本身可以改变,可以指向另外的对象。
    int m;
    const int *pm = &m;  // pm 是指向常量的指针

    int n;
    pm = &n;  // 操作正确,pm 本身的值可以改变
    //*pm = 1;  // 编译时会报错,不能通过pm改变所指的对象

    /*   指针常量,则指针本身的值不能被改变。        */
     int b;
     int * const pb = &b;
    //pb = &m;  // 会报错,pb 是指针常量,其值(表示的地址)不能被改变,就是不能再用其他变量的地址赋值给该指针


    system("pause");
    return 0;

}

  • 示例6:

/*************************************************
*
**Description: 了解 void 类型指针的 使用
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-6.cpp
** 
***************************************************/
#include<iostream>
using namespace std;
int main(){
    // void 类型的指针使用
    //!	void voidObject;	//错,不能声明void类型的变量
    void *pv;      // 声明 void 类型的指针
    int a = 5;
    pv = &a;       // 取整型变量的地址赋给void类型指针
    int *pint = static_cast<int*>(pv);    // void 类型指针转换为 int 型指针
    cout << " *pint=  " << *pint << endl;
    system("pause");
    return 0;

}

  • 示例7:

/*************************************************
*
**Description://  尝试3循环遍历数组元素的3种不同方法,了解指针运算与指针变量的使用
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-7.cpp
** 
***************************************************/
#include <iostream>
using namespace std;

int main() {

    // 第一种:数组名和下标
	int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
	for (int i = 0; i < 10; i++)
		cout << a[i] << "  ";
	cout << endl;

    //第二种:数组名和指针运算
	for (int i = 0; i < 10; i++)
		cout << *(a+i) << "  ";
	cout << endl;

    //第三种:使用指针变量
    for (int *p = a; p < (a + 10); p++)
        cout << *p << "  ";
	cout << endl;

    system("pause");
	return 0;
}

// 使用指针运算,逐个输出二维数组第i行元素值
// #include <iostream>
// using namespace std;

// int main() {
// 	int array2[3][3]= { { 11, 12, 13 }, { 21, 22, 23 }, { 31, 32, 33 } };
// 	for(int i = 0; i < 3; i++) {
// 		for(int j = 0; j < 3; j++)
// 			cout << *(*(array2 + i) + j) << " ";	//逐个输出二维数组第i行元素值
// 		cout << endl;
// 	}
//     system("pause");
// 	return 0;
// }


  • 示例8:

/*************************************************
*
**Description:// 利用指针数组存放矩阵,了解指针数组的表示与常规数组的区别
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-8.cpp
** 
***************************************************/

#include<iostream>
using namespace std;
int main(){
    int line1[]={1,0,0};   //矩阵的第1行
    int line2[]={0,1,0};   //矩阵的第2行
    int line3[]={0,0,1};   //矩阵的第3行

    // 定义整型指针数组并初始化
    int *pline[3]={line1,line2,line3};   //因为一维数组的数组名就是数组的首地址,可以用来初始化指针
    cout << " Matrix test: " << endl;

    //使用指针数组输出矩阵
    for(int i=0;i<3;i++){
        for (int j=0;j<3;j++)
            cout << pline[i][j] << "  ";//输出每一行(依次输出每个一维矩阵)
        cout << endl;   // 注意缩进,在输出每一行以后,要换行
        
    }
    system("pause");
    return 0;

}

  • 示例9:

/*************************************************
*
**Description:// 将实数x分成整数部分和小数部分的实现,了解利用指针作参数的使用,达到数据的双向传递,传递到一组数据,只传首地址运行效率比较高
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-9.cpp
** 
***************************************************/

#include <iostream>
using namespace std;

//将实数x分成整数部分和小数部分,形参intpart、fracpart是指针
void splitFloat(float x, int *intPart, float *fracPart) {
	*intPart = static_cast<int>(x);	//取x的整数部分
	*fracPart = x - *intPart;		//取x的小数部分
}

int main() {
	cout << "Enter 3 float point numbers:" << endl;
	for(int i = 0; i < 3; i++) {   // 连续输入3各浮点数进行分割
		float x, f;
		int n;
		cin >> x;
		splitFloat(x, &n, &f);	//变量地址作为实参
		cout << "Integer Part = " << n << " Fraction Part = " << f << endl;
	}
    system("pause");
	return 0;
}

  • 示例10:



/*************************************************
*
**Description:// // 函数指针举例: 了解指向函数的指针 的使用--实现函数的回调
在声明一个指向函数的指针同时要声明:,还要规定这个函数的参数表是什么样的;以及函数的返回类型
    //以下通过定义一个compute函数,实现函数的回调,通过一个函数来实现不同的功能
(取不同函数地址来实现功能)

** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-10.cpp
** 
***************************************************/
#include<iostream>
using namespace std;
int compute(int a, int b,int(*func)(int,int))
{return func(a,b);}

int max(int a, int b) // 求最大值
{return ((a>b)?a:b);}

int min(int a, int b) // 求最小值
{return ((a<b)?a:b);}

int sum(int a, int b) // 求和
{return (a+b);}


int main(){
    int a,b,res;
    cout << "请输入整数 a :";
    cin >> a;
    cout << "请输入整数 b :";
    cin >> b;

    res = compute(a,b,&max);  // 将计算最大值的函数所在的地址取到
    cout << "Max of  " << a << " and " << b << " is " <<  res << endl;

    res = compute(a,b,&min);  // 将计算最小值的函数所在的地址取到
    cout << "Min of  " << a << " and " << b << " is " <<  res << endl;

    res = compute(a,b,&sum);  // 将计算求和函数所在的地址取到
    cout << "Sum of  " << a << " and " << b << " is " <<  res << endl;

    system("pause");
}

  • 示例11:


/*************************************************
*
**Description://了解对象指针的定义和使用,通过对象指针访问类中的成员函数
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-11.cpp
** 
***************************************************/
#include<iostream>
using namespace std;

class Point{
public:
    Point(int x=0, int y=0):x(x),y(y){}  // 构造函数
    int getX() const{return x;}          // 取值函数
    int getY() const{return y;}

private:
 int x,y;
 };

 int main(){
     Point a(4,5);
     Point *p1 = &a;  //定义对象指针,用a的地址初始化
     cout << " p1->getX(): " << p1->getX() << endl;  //用指针访问对象成员
     cout<< " a.getX()(): " << a.getX() << endl;    //用对象名访问对象成员

     system("pause");
     return 0;
 }

//  #include <iostream>
// using namespace std;

// class Point {	//类的定义
// public:	//外部接口
// 	Point(int x = 0, int y = 0) : x(x), y(y) { }	//构造函数
// 	int getX() const { return x; }	//返回x
// 	int getY() const { return y; }	//返回y
// private:	//私有数据
// 	int x, y;
// };

// int main() {	//主函数
// 	Point a(4,5);	//定义对象A
// 	Point *p1 = &a;	//定义对象指针并初始化
// 	int (Point::*funcPtr)() const = &Point::getX;	//定义成员函数指针并初始化
	
// 	cout << (a.*funcPtr)() << endl;		//(1)使用成员函数指针和对象名访问成员函数
// 	cout << (p1->*funcPtr)() << endl;	//(2)使用成员函数指针和对象指针访问成员函数
// 	cout << a.getX() << endl;			//(3)使用对象名访问成员函数
// 	cout << p1->getX() << endl;			//(4)使用对象指针访问成员函数

// 	return 0;
// }


  • 示例12:
/*************************************************
*
**Description:直接通过指针 :访问类的静态数据成员、类的静态函数成员
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-12.cpp
** 
***************************************************/

//使用指针 访问类的静态数据成员
#include <iostream>
using namespace std;

class Point {	//Point类定义
public:	//外部接口
	Point(int x = 0, int y = 0) : x(x), y(y) { //构造函数
		count++;
	}	
	Point(const Point &p) : x(p.x), y(p.y) {	//拷贝构造函数
		count++;
	}
	~Point() {  count--; }
	int getX() const { return x; }
	int getY() const { return y; }
	static int count;	//静态数据成员声明,用于记录点的个数

private:	//私有数据成员
	int x, y;
};

int Point::count = 0;	//静态数据成员定义和初始化,使用类名限定

int main() {	//主函数实现
	int *ptr = &Point::count;	//定义一个int型指针,指向类的静态成员
	Point a(4, 5);	//定义对象a
	cout << "Point A: " << a.getX() << ", " << a.getY();
	cout << " Object count = " << *ptr << endl;	//直接通过指针访问静态数据成员

	Point b(a);	//定义对象b
	cout << "Point B: " << b.getX() << ", " << b.getY();
	cout << " Object count = " << *ptr << endl; 	//直接通过指针访问静态数据成员

	return 0;
}




//  使用指针,访问类的静态函数成员
#include <iostream>
using namespace std;

class Point {	//Point类定义
public:	//外部接口
	Point(int x = 0, int y = 0) : x(x), y(y) { //构造函数
		count++;
	}	
	Point(const Point &p) : x(p.x), y(p.y) {	//拷贝构造函数
		count++;
	}
	~Point() {  count--; }
	int getX() const { return x; }
	int getY() const { return y; }

	static void showCount() {		//输出静态数据成员
		cout << "  Object count = " << count << endl;
	}

private:	//私有数据成员
	int x, y;
	static int count;	//静态数据成员声明,用于记录点的个数
};

int Point::count = 0;	//静态数据成员定义和初始化,使用类名限定

int main() {	//主函数实现
	void (*funcPtr)() = Point::showCount;	//定义一个指向函数的指针,指向类的静态成员函数

	Point a(4, 5);	//定义对象A
	cout << "Point A: " << a.getX() << ", " << a.getY();
	funcPtr();	//输出对象个数,直接通过指针访问静态函数成员

	Point b(a);	//定义对象B
	cout << "Point B: " << b.getX() << ", " << b.getY();
	funcPtr();	//输出对象个数,直接通过指针访问静态函数成员

	return 0;
}

  • 示例13:


/*************************************************
*
**Description:动态分配内存的声明使用示例:为对象申请动态分配内存来存储,并及时 删除内存
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-13.cpp
** 
***************************************************/
#include <iostream>
using namespace std;
class Point {
public:
	Point() : x(0), y(0) {   // 默认构造函数
	cout<<"Default Constructor called."<<endl;
}
    Point(int x, int y):x(x),y(y){    // 构造函数
    cout << "Constructor called."<< endl;
}
    ~Point() { cout<<"Destructor called."<<endl; }
    int getX() const {return x;}
    int getY() const {return y;}
    void move(int newX, int newY){
        x = newX;
        y = newY;
    }
private:
    int  x,y;
};

int main (){
    cout << "Step one: " << endl;
    Point *ptr1 = new Point;  // 调用默认构造函数,生成点  
    delete ptr1;   // 删除对象,自动调用析构函数,删除的是指针指向的空间,不是删除指针本身

    cout << "Step two: " << endl;
    ptr1 = new Point(1,2);  // 调用构造函数,再次生成一个点  
    delete ptr1;

    system("pause");
    return 0;
}





// 动态创建对象数组

#include <iostream>
using namespace std;
class Point {
public:
	Point() : x(0), y(0) {   // 默认构造函数
	cout<<"Default Constructor called."<<endl;
}
    Point(int x, int y):x(x),y(y){    // 构造函数
    cout << "Constructor called."<< endl;
}
    ~Point() { cout<<"Destructor called."<<endl; }
    int getX() const {return x;}
    int getY() const {return y;}
    void move(int newX, int newY){
        x = newX;
        y = newY;
    }
private:
    int  x,y;
};
int main (){
    // cout << "Step one: " << endl;
    Point *ptr = new Point[2];  // 调用默认构造函数,创建对象数组 
    ptr[0].move(5,10);   // 通过指针访问数组元素的成员
    ptr[1].move(15,20);   // 通过指针访问数组元素的成员
    cout << " Deleting "<< endl;
    delete[] ptr;   // 删除整个对象数组
    /*注意: [ ]  必须要带,没有【】,仅仅是释放数组首元素的地址,带有【】,才会释放整个数组*/
    cout<< "ptr[0]X"<< ptr[0].getX()<< endl;
    cout<< "ptr[0]"<< ptr<< endl;
    
    system("pause");
    return 0;

}


  • 示例14:
/*************************************************
*
**Description:动态创建多维数组示例
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-14.cpp
** 
***************************************************/
#include <iostream>
using namespace std;

int main (){

    int (*cp)[9][8] = new int[7][9][8];  // 用指向数组的指针创建多维数组
    // 给数组各个位置赋值
    for (int i=0;i<7;i++)
       for(int j=0;j<9;j++)
           for(int k=0;k<8;k++)
           *(*(*(cp+i)+j)+k) = (i*100+j*10+k);
    //显示数组
    for (int i=0;i<7;i++){    
       for(int j=0;j<9;j++){             
           for(int k=0;k<8;k++)
             cout << cp[i][j][k] << "  ";
           cout << endl;
        }
        cout << endl;
    }
    delete[] cp;   // 释放动态数组
    system("pause");
    return 0;

}

  • 示例15:
/*************************************************
*
**Description:动态数组类示例:将动态数组封装成类,更加简洁,便于管理,也可以在访问数组元素前检查下标是否越界
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-15.cpp
** 
***************************************************/
#include <iostream>
#include<cassert>
using namespace std;

class Point {   // 创建点 类
public:
	Point() : x(0), y(0) {   // 默认构造函数
	cout<<"Default Constructor called."<<endl;
    }
    Point(int x, int y):x(x),y(y){    // 构造函数
    cout << "Constructor called."<< endl;
    }
    ~Point() { 
        cout<<"Destructor called."<<endl; 
        }
    int getX() const {return x;}
    int getY() const {return y;}
    void move(int newX, int newY){
        x = newX;
        y = newY;
    }
private:
    int  x,y;
};
class ArrayOfPoints{  //  动态数组类
public:
    ArrayOfPoints(int size):size(size){     // 构造函数
        points = new Point[size];
    }
    ~ArrayOfPoints(){       // 析构函数,释放动态内存
        cout << " Deleting...... " << endl;
        delete[] points;
    }
    Point&element(int index){   //在不超出范围的情况下,返回数组索引值(返回的是  引用 类型,可以进行修改)
        assert(index >=0 && index < size);
        return points[index];
    }
private:
    Point *points;    // 指向动态数组首地址
    int size;     // 数组 大小
};
int main (){
    int count;
    cout << " 请输入创建点的个数:" ;
    cin >> count;
    ArrayOfPoints points(count);    //  创建数组对象
    points.element(0).move(5,0);   // 访问数组元素的成员
    points.element(1).move(13,29);  // 访问数组元素的成员  (这里,element函数返回对象的引用,已经改变了封装以后数组内部的元素)

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

}


  • 示例16:
/*************************************************
*
**Description:// 利用指针,动态分配生成三维数组(8组9行8列)
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-16.cpp
** 
***************************************************/

#include <iostream>
using namespace std;
int main() {
	float (*cp)[9][8] = new float[8][9][8];
    // 生成数组元素
	for (int i = 0; i < 8; i++)
		for (int j = 0; j < 9; j++)
			for (int k = 0; k < 8; k++)
				//以指针形式数组元素
				*(*(*(cp + i) + j) + k) = static_cast<float>(i * 100 + j * 10 + k);
    // 依次打印出
	for (int i = 0; i < 8; i++) {
		for (int j = 0; j < 9; j++) {
			for (int k = 0; k < 8; k++)
				//将指针cp作为数组名使用,通过数组名和下标访问数组元素
				cout << cp[i][j][k] << "  ";
			cout << endl;
		}
		cout << endl;
	}
	delete[] cp;  // 删除内存
    system("pause");
	return 0;
}


  • 示例17:
/*************************************************
*
**Description:vector 示例 :了解vector的声明使用 与 元素遍历访问的方法
    基于范围的for循环配合auto

** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-17.cpp
** 
***************************************************/
// 计算vecto中的数组arr元素的平均值 
#include<iostream>
#include<vector>
using namespace std;

double average(const vector<double> &arr){
    double sum = 0;
    for(unsigned i=0;i<arr.size();i++)
        sum += arr[i];
    return sum/arr.size(); 
}

int main(){
    unsigned n;
    cout << " Pelease input the number of array: " << endl;
    cout << " n= ";
    cin >> n;

    vector<double>arr(n);   // 创建数组对象
    cout << " Pelease input " << n << " real numbers: " << endl;
    for (unsigned i=0;i<n;i++)
        cin >> arr[i];

    cout <<" 遍历数组元素,方法1:  "<endl;
    for(auto i=arr.begin();i!=arr.end();i++)
        cout << *i << endl;

    cout <<" 遍历数组元素,方法2:  "<< endl;
    for(auto e:arr)
        cout << e << endl;    

    cout << "Average = " << average(arr) << endl;
    system("pause");
    return 0;
}


  • 示例18:
/*************************************************
*
**Description:vector 示例 : 浅复制 举例

** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-18.cpp
** 
***************************************************/v
#include<iostream>
#include<cassert>
using namespace std;

class Point {
public:
	Point() : x(0), y(0) {   // 默认构造函数
	cout<<"Default Constructor called."<<endl;
}
    Point(int x, int y):x(x),y(y){    // 构造函数
    cout << "Constructor called."<< endl;
}
    ~Point() { cout<<"Destructor called."<<endl; }
    int getX() const {return x;}
    int getY() const {return y;}
    void move(int newX, int newY){
        x = newX;
        y = newY;
    }
private:
    int  x,y;
};

class ArrayOfPoints{  //  动态数组类
public:
    ArrayOfPoints(int size):size(size){     // 构造函数
        points = new Point[size];
    }
    ~ArrayOfPoints(){       // 析构函数,释放动态内存
        cout << " Deleting...... " << endl;
        delete[] points;

    }
    Point&element(int index){   //在不超出范围的情况下,返回数组索引值(返回的是  引用 类型,可以进行修改)
        assert(index >=0 && index < size);
        return points[index];
    }
private:
    Point *points;    // 指向动态数组首地址
    int size;     // 数组 大小

};

int main(){
    int count;
    cout << " please enter the count of points: " ;
    cin >> count;
    ArrayOfPoints pointsArray1(count);  //创建对象数组
    pointsArray1.element(0).move(5,10);
    pointsArray1.element(1).move(15,20);

    ArrayOfPoints pointsArray2(pointsArray1);  // 创建副本(浅复制--默认复制构造函数)

    cout << " copy of pointsArray1 : " << endl;

    cout << "Point_0 of array2: " << pointsArray2.element(0).getX()<<","
         << pointsArray2.element(0).getY() << endl;

    cout << "Point_1 of array2: " << pointsArray2.element(1).getX()<<","
         << pointsArray2.element(1).getY() << endl;
    
    pointsArray1.element(0).move(25,30);
    pointsArray1.element(1).move(35,40);

    cout << " After the moving of pointsArray1:  "  << endl;

    cout << "Point_0 of array2: " << pointsArray2.element(0).getX()<<","
         << pointsArray2.element(0).getY() << endl;

    cout << "Point_1 of array2: " << pointsArray2.element(1).getX()<<","
         << pointsArray2.element(1).getY() << endl;

    system("pause");  
    return 0;
}
  // 程序会在结束时,清除内存时候报错,浅复制,两个数组实际指向同一个内存单元

  • 示例19:

/*************************************************
*
**Description:vector 示例 : 对象 深层复制 举例 

** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-19.cpp
** 
***************************************************/
#include<iostream>
#include<cassert>
using namespace std;

class Point {
public:
	Point() : x(0), y(0) {   // 默认构造函数
	cout<<"Default Constructor called."<<endl;
}
    Point(int x, int y):x(x),y(y){    // 构造函数
    cout << "Constructor called."<< endl;
}
    ~Point() { cout<<"Destructor called."<<endl; }
    int getX() const {return x;}
    int getY() const {return y;}
    void move(int newX, int newY){
        x = newX;
        y = newY;
    }
private:
    int  x,y;
};

class ArrayOfPoints{  //  动态数组类
public:

	ArrayOfPoints(int size) : size(size) { //默认构造函数
		points = new Point[size];
	}
    ArrayOfPoints(const ArrayOfPoints& pointsArray);   // 自定义构造函数

    ~ArrayOfPoints(){       // 析构函数,释放动态内存
        cout << " Deleting...... " << endl;
        delete[] points;

    }
    Point&element(int index){   //在不超出范围的情况下,返回数组索引值(返回的是  引用 类型,可以进行修改)
        assert(index >=0 && index < size);
        return points[index];
    }
private:
    Point *points;    // 指向动态数组首地址
    int size;     // 数组 大小
};
// 重新自定义的复制构造函数(深复制)
ArrayOfPoints:: ArrayOfPoints(const ArrayOfPoints& v){
    size = v.size;
    points = new Point[size]; // 指针的值不能直接赋值,构造一个动态数组,将动态数组首地址寄放在正在构造的points指针里
    // for 循环将参数数组里的每个元素值一 一赋值给当前对象(这样,是真的复制过来,复制的值同样占据了内存空间)
    for (int i=0;i<size;i++)
        points[i]=v.points[i];
}

int main(){
    int count;
    cout << " please enter the count of points: " ;
    cin >> count;
    ArrayOfPoints pointsArray1(count);  //创建对象数组
    pointsArray1.element(0).move(5,10);
    pointsArray1.element(1).move(15,20);

    ArrayOfPoints pointsArray2(pointsArray1);  // 创建副本(浅复制--复制构造函数)

    cout << " copy of pointsArray1 : " << endl;

    cout << "Point_0 of array2: " << pointsArray2.element(0).getX()<<","
         << pointsArray2.element(0).getY() << endl;

    cout << "Point_1 of array2: " << pointsArray2.element(1).getX()<<","
         << pointsArray2.element(1).getY() << endl;
    
    pointsArray1.element(0).move(25,30);
    pointsArray1.element(1).move(35,40);

    cout << " After the moving of pointsArray1:  "  << endl;

    cout << "Point_0 of array2: " << pointsArray2.element(0).getX()<<","
         << pointsArray2.element(0).getY() << endl;

    cout << "Point_1 of array2: " << pointsArray2.element(1).getX()<<","
         << pointsArray2.element(1).getY() << endl;

    system("pause");  
    return 0;
}


  • 示例20:

/*************************************************
*
**Description:vector 示例 :string 字符 串举例

** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-20.cpp
** 
***************************************************/
#include<iostream>
#include<string>
using namespace std;

//根据value的值输出true或false
//title为提示文字

inline void test(const char *title, bool value){
    cout << title << " returns " << (value ? "true":"false") << endl;
}

int main(){
    string s1 = "DEF";
    string s2;
    cout << "Please enter s2: ";
    cin >> s2;
    cout << "length of s2: " << s2.length() << endl;

    //比较运算符的测试
    test("s1 <= \"ABC\"", s1 <= "ABC");
    test("\"DEF\" <= s1", "DEF" <= s1);

    // //连接运算符的测试
    // s2 += s1;
    // cout << "s2 = s2 + s1: " << s2 << endl;
    // cout << "length of s2: " << s2.length() << endl;
    system("pause");
    return 0;
}


  • 示例21:

/*************************************************
*
**Description:vector 示例 :使用getline 整行输入字符串(包含头文件string)输入
字符串时,可以使用其它分隔符作为字符串结束的标志(例如逗号、分号),将分隔符作为getline的第3个参数即可,例如:getline(cin, s2, ',');(默认空格为分隔符)
** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-21.cpp
** 
***************************************************/
#include<iostream>
#include<string>
using namespace std;

int main(){
    for (int i = 0; i < 2; i++){
        string city, state;
        cout << " 请输入城市名称以及所属国家,用 ',' 分隔  : " << endl;
        getline(cin, city, ',');
        getline(cin, state);
        cout << "City:" << city << " State:" << state << endl;
	}
    system("pause");
    return 0;
}


  • 示例22:

/*************************************************
*
**Description:综合示例:创建个人银行账户管理程序
   涉及综合知识点::数组,指针,字符串等,采用工程开发机制,多文件代码

** Author:慕灵阁-wupke
** Time:2021-12-15
** Versions :5-22.cpp
** 
***************************************************/

// main.cpp
#include "account.h"
#include <iostream>
using namespace std;

int main() {
	Date date(2008, 11, 1);	//起始日期
	//建立几个账户
	SavingsAccount accounts[] = {
		SavingsAccount(date, "S3755217", 0.015),
		SavingsAccount(date, "02342342", 0.015)
	};
	const int n = sizeof(accounts) / sizeof(SavingsAccount); //账户总数
	//11月份的几笔账目
	accounts[0].deposit(Date(2008, 11, 5), 5000, "salary");
	accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
	//12月份的几笔账目
	accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
	accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");

	//结算所有账户并输出各个账户信息
	cout << endl;
	for (int i = 0; i < n; i++) {
		accounts[i].settle(Date(2009, 1, 1));
		accounts[i].show();
		cout << endl;
	}
	cout << "Total: " << SavingsAccount::getTotal() << endl;
	return 0;
}




//account.cpp
#include "account.h"
#include <cmath>
#include <iostream>
using namespace std;

double SavingsAccount::total = 0;

//SavingsAccount类相关成员函数的实现
SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
	: id(id), balance(0), rate(rate), lastDate(date), accumulation(0) {
	date.show();
	cout << "\t#" << id << " created" << endl;
}

void SavingsAccount::record(const Date &date, double amount, const string &desc) {
	accumulation = accumulate(date);
	lastDate = date;
	amount = floor(amount * 100 + 0.5) / 100;	//保留小数点后两位
	balance += amount;
	total += amount;
	date.show();
	cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void SavingsAccount::error(const string &msg) const {
	cout << "Error(#" << id << "): " << msg << endl;
}

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
	record(date, amount, desc);
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
	if (amount > getBalance())
		error("not enough money");
	else
		record(date, -amount, desc);
}

void SavingsAccount::settle(const Date &date) {
	double interest = accumulate(date) * rate	//计算年息
		/ date.distance(Date(date.getYear() - 1, 1, 1));
	if (interest != 0)
		record(date, interest, "interest");
	accumulation = 0;
}

void SavingsAccount::show() const {
	cout << id << "\tBalance: " << balance;
}






//account.h
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
#include "date.h"
#include <string>

class SavingsAccount { //储蓄账户类
private:
	std::string id;		//帐号
	double balance;		//余额
	double rate;		//存款的年利率
	Date lastDate;		//上次变更余额的时期
	double accumulation;	//余额按日累加之和
	static double total;	//所有账户的总金额

	//记录一笔帐,date为日期,amount为金额,desc为说明
	void record(const Date &date, double amount, const std::string &desc);
	//报告错误信息
	void error(const std::string &msg) const;
	//获得到指定日期为止的存款金额按日累积值
	double accumulate(const Date& date) const {
		return accumulation + balance * date.distance(lastDate);
	}
public:
	//构造函数
	SavingsAccount(const Date &date, const std::string &id, double rate);
	const std::string &getId() const { return id; }
	double getBalance() const { return balance; }
	double getRate() const { return rate; }
	static double getTotal() { return total; }

	//存入现金
	void deposit(const Date &date, double amount, const std::string &desc);
	//取出现金
	void withdraw(const Date &date, double amount, const std::string &desc);
	//结算利息,每年1月1日调用一次该函数
	void settle(const Date &date);
	//显示账户信息
	void show() const;
};

#endif //__ACCOUNT_H__







//date.cpp
#include "date.h"
#include <iostream>
#include <cstdlib>
using namespace std;

namespace {	//namespace使下面的定义只在当前文件中有效
	//存储平年中某个月1日之前有多少天,为便于getMaxDay函数的实现,该数组多出一项
	const int DAYS_BEFORE_MONTH[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
}

Date::Date(int year, int month, int day) : year(year), month(month), day(day) {
	if (day <= 0 || day > getMaxDay()) {
		cout << "Invalid date: ";
		show();
		cout << endl;
		exit(1);
	}
	int years = year - 1;
	totalDays = years * 365 + years / 4 - years / 100 + years / 400
		+ DAYS_BEFORE_MONTH[month - 1] + day;
	if (isLeapYear() && month > 2) totalDays++;
}

int Date::getMaxDay() const {
	if (isLeapYear() && month == 2)
		return 29;
	else
		return DAYS_BEFORE_MONTH[month]- DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
	cout << getYear() << "-" << getMonth() << "-" << getDay();
}




//date.h
#ifndef __DATE_H__
#define __DATE_H__

class Date {	//日期类
private:
	int year;		//年
	int month;		//月
	int day;		//日
	int totalDays;	//该日期是从公元元年1月1日开始的第几天

public:
	Date(int year, int month, int day);	//用年、月、日构造日期
	int getYear() const { return year; }
	int getMonth() const { return month; }
	int getDay() const { return day; }
	int getMaxDay() const;		//获得当月有多少天
	bool isLeapYear() const {	//判断当年是否为闰年
		return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	}
	void show() const;			//输出当前日期
	//计算两个日期之间差多少天	
	int distance(const Date& date) const {
		return totalDays - date.totalDays;
	}
};

#endif //__DATE_H__





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值