例如:int a[10];
表示a为整型数组,有10个元素:a[0]...a[9]
例如: int a[5][3];
表示a为整型二维数组,其中第一维有5个下标(0~4),第二维有3个下标(0~2),数组的元素个数为15,可以用于存放5行3列的整型数据表格。
必须先声明,后使用。
只能逐个引用数组元素,而不能一次引用整个数组
例如:a[0]=a[5]+a[7]-a[2*3]
例如:b[1][2]=a[2][3]/2
例:
#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; } return 0; }
在定义数组时给出数组元素的初始值。
列出全部元素的初始值
例如:static int a[10]={0,1,2,3,4,5,6,7,8,9};
可以只给一部分元素赋初值
例如:static int a[10]={0,1,2,3,4};
在对全部数组元素赋初值时,可以不指定数组长度
例如:static int a[]={0,1,2,3,4,5,6,7,8,9}
按行存放
例如: float a[3][4];
可以理解为:
其中数组a的存储顺序为:
a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23
将所有初值写在一个{}内,按顺序初始化
例如:static int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12
分行列出二维数组元素的初值
例如:static int a[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
可以只对部分元素初始化
例如:static int a[3][4]={{1},{0,6},{0,0,11}};
列出全部初始值时,第1维下标个数可以省略
例如:static int a[][4]={1,2,3,4,5,6,7,8,9,10,11,12};
或:static int a[][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}};
注意:
#include <iostream> using namespace std; int main() { int f[20] = {1,1}; //初始化第0、1个数 for (int i = 2; i < 20; i++) //求第2~19个数 f[i] = f[i - 2] + f[i - 1]; for (int i=0;i<20;i++) { //输出,每行5个数 if (i % 5 == 0) cout << endl; cout.width(12); //设置输出宽度为12 cout << f[i]; } return 0; }
运行结果:
#include <iostream> using namespace std; void rowSum(int a[][4], int nRow) { //计算二维数组a每行的值的和,nRow是行数 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 << "Sum of row " << i << " is " << table[i][0] << endl; return 0; }
//Point.h #ifndef _POINT_H #define _POINT_H class Point { //类的定义 public: //外部接口 Point(); Point(int x, int y); ~Point(); void move(int newX,int newY); int getX() const { return x; } int getY() const { return y; } static void showCount(); //静态函数成员 private: //私有数据成员 int x, y; }; #endif //_POINT_H
//Point.cpp #include <iostream> #include "Point.h" using namespace std; Point::Point() : x(0), y(0) { cout << "Default Constructor called." << endl; } Point::Point(int x, int y) : x(x), y(y) { cout << "Constructor called." << endl; } Point::~Point() { cout << "Destructor called." << endl; } void Point::move(int newX,int newY) { cout << "Moving the point to (" << newX << ", " << newY << ")" << endl; x = newX; y = newY; }
//6-3.cpp #include "Point.h" #include <iostream> using namespace std; int main() { cout << "Entering main..." << endl; Point a[2]; for(int i = 0; i < 2; i++) a[i].move(i + 10, i + 20); cout << "Exiting main..." << endl; return 0; }
基于范围的for循环
//POint.h #pragma once #ifndef _POINT_H #define _POINT_H class Point { public: Point(float x = 0, float y = 0) :x(x), y(y) {}; float getX() const { return x; } float getY() const { return y; } private: float x, y; }; #endif // !_POINT_H
// 程序实例6-4.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include "Point.h" #include <iostream> #include <cmath> using namespace std; //直线线性拟合,point为各点,nPoint为点数 float lineFit(const Point points[], int nPoint) { float avgX = 0, avgY = 0; float lxx = 0, lyy = 0, lxy = 0; for (int i = 0; i < nPoint; i++) { avgX += points[i].getX() / nPoint; //计算x,y平均值 avgY += points[i].getY() / nPoint; } for (int i = 0; i < nPoint; i++) { lxx += (points[i].getX() - avgX)*(points[i].getX() - avgX); lyy += (points[i].getY() - avgY)*(points[i].getY() - avgY); lxy += (points[i].getX() - avgX)*(points[i].getY() - avgY); } cout << "This line can be fitted bu y=ax+b" << endl; cout << "a=" << lxy / lxx << " "; //输出回归系数a cout << "b=" << avgY - lxy * avgX / lxx << endl;//输出回归系数b return static_cast<float>(lxy / sqrt(lxx*lyy));//返回相关系数r } int main() { Point p[10] = { Point(6,10), Point(14,20), Point(26,30), Point(33,40), Point(46,50), Point(54,60), Point(67,70), Point(75,80), Point(100,100) }; float r = lineFit(p, 10); //进行线性回归计算 cout << "Line coefficient r="<<r<< endl; return 0; }
#include<iostream> using namespace std; void main() { int *i_pointer; //声明int型指针i_pointer int i; //声明int型数i i_pointer=&i; //取i的地址赋给i_pointer i=10; //int型数赋初值 cout<<"Output int i="<<i<<endl; //输出int型数的值 cout<<"Output int pointer i="<<*i_pointer<<endl; //输出int型指针所指地址的内容 }
关于指针类型,还需要注意:
int a; const int *pl=&a; //pl是指向常量的指针 int b; pl = &b; //正确,pl本身的值可以改变 *pl=1; //编译时出错,不能通过pl改变所指向的对象
2、可以声明指针类型的常量,这时指针本身的值不能被改变。
int *const p2=&a; p2=&b; //错误,p2是指针常量,值不能改变
1、一般情况下,指针的值只能赋给相同类型的指针。但是有一种特殊的void类型指针,可以存储任何类型的对象地址,就是说任何类型的指针都可以赋值给void类型的指针变量。经过使用类型显式转换,通过void类型的指针便可以访问任何类型的数据。
void vobject; //错,不能声明void类型的变量 void *pv; //对,可以声明void类型的指针 int i=5; void main() //void类型的函数没有返回值 { pv = &i; //void类型指针指向整型变量 int *pint = (int *)pv; // void指针赋值给int指针需要类型强制转换: }
//使用数组名和下标 main() { int a[10]; int i; for(i=0; i<10; i++) cin>>a[i]; cout<<endl; for(i=0; i<10; i++) cout<<a[i]; } //使用数组名和指针运算 main() { int a[10]; int i; for(i=0; i<10; i++) cin>>a[i]; cout<<endl; for(i=0; i<10; i++) cout<<*(a+i); } //使用指针变量 main() { int a[10]; int *p,i; for(i=0; i<10; i++) cin>>a[i]; cout<<endl; for(p=a; p<(a+10); p++) cout<<*p; }
#include <iostream> using namespace std; void main() { int line1[]={1,0,0}; //声明数组,矩阵的第一行 int line2[]={0,1,0}; //声明数组,矩阵的第二行 int line3[]={0,0,1}; //声明数组,矩阵的第三行 int *p_line[3]={line1,line2,line3}; //声明整型指针数组并初始化指针数组元素 cout<<"Matrix test:"<<endl; //输出单位矩阵 for(int i=0;i<3;i++) //对指针数组元素循环 { for(int j=0;j<3;j++) //对矩阵每一行循环 { cout<<p_line[i][j]<<" "; } cout<<endl; } }
输出结果为:
#include <iostream> using namespace std; void main() { int array2[2][3]={{11,12,13},{21,22,23}}; for(int i=0;i<2;i++) { cout<<*(array2+i)<<endl; for(int j=0;j<3;j++) { cout<<*(*(array2+i)+j)<<" "; //或者 cout<<array2[i][j]<<" "; } cout<<endl; } }
#include <iostream> using namespace std; //将实数X分成整数部分和小数部分,形参inPart、fracPart是指针 void splitfloat(float x, int *intpart, float *fracpart) { //形参intpart、 fracpart是指针 *intpart = int(x); // 取x的整数部分 *fracpart = x - *intpart; //取x的小数部分 } void main(void) { int i, n; float x, f; cout << "Enter three (3) floating point numbers"<< endl; for (i = 0; i < 3; i++) { cin >> x; splitfloat(x,&n,&f); //变量地址做实参 cout << "Integer Part is " << n << " Fraction Part is " << f << endl; } }
例:输出数组元素的内容和地址
#include <iostream> #include <iomanip> using namespace std; void Array_Ptr(long *P, int n) { int i; cout << "In func, address of array is " << unsigned long(P) << endl; cout << "Accessing array in the function using pointers"<< endl; for (i = 0; i < n; i++) { cout << " Address for index " << i << " is " << unsigned long(P+i); cout << " Value is " << *(P+i) << endl; } } void main(void) { long list[5] = {50, 60, 70, 80, 90}; cout << "In main, address of array is " << unsigned long(list) << endl; cout << endl; Array_Ptr(list,5); }
运行结果:
#include<iostream> using namespace std; const int N=6; void print(const int *p,int n); void main() { int array[N]; for(int i=0;i<N;i++) cin>>array[i]; print(array,N); } void print(const int *p, int n) { cout<<"{"<<*p; for(int i=1;i<n;i++) cout<<"."<<*(p+i); cout<<"}"<<endl; }
#include <iostream> using namespace std; void print_stuff(float data_to_ignore); void print_message(float list_this_data); void print_float(float data_to_print); void (*function_pointer)(float); void main() { float pi = (float)3.14159; float two_pi = (float)2.0 * pi; print_stuff(pi); function_pointer = print_stuff; function_pointer(pi); function_pointer = print_message; function_pointer(two_pi); function_pointer(13.0); function_pointer = print_float; function_pointer(pi); print_float(pi); } void print_stuff(float data_to_ignore) { cout<<"This is the print stuff function.\n"; } void print_message(float list_this_data) { cout<<"The data to be listed is " <<list_this_data<<endl; } void print_float(float data_to_print) { cout<<"The data to be printed is " <<data_to_print<<endl; }
运行结果:
int main() { Point A(5,10); Point *ptr; ptr=&A; int x; x=ptr->GetX(); cout<<x<<endl; return 0; }
曾经出现过的错误例子:
class Fred; //前向引用声明 class Barney { Fred x; //错误:类Fred的声明尚不完善 }; class Fred { Barney y; };
正确程序:
class Fred; //前向引用声明 class Barney { Fred *x; }; class Fred { Barney y; };
void main() //主函数 { Point A(4,5); //声明对象A Point *p1=&A; //声明对象指针并初始化 int (Point::*p_GetX)()=Point::GetX; //声明成员函数指针并初始化 cout<<(A.*p_GetX)()<<endl; //(1)使用成员函数指针访问成员函数 cout<<(pl->*p_GetX)()<<endl; //(2)使用成员函数指针和对象指针访问成员函数 cout<<(p1->GetX)()<<endl; //(3)使用对象指针访问成员函数 cout<<A.GetX()<<endl; //(4)使用对象名访问成员函数 }
#include <iostream> using namespace std; class Point //Point类声明 {public: //外部接口 Point(int xx=0, int yy=0) {X=xx;Y=yy;countP++;}//构造函数 Point(Point &p); //拷贝构造函数 int GetX() {return X;} int GetY() {return Y;} static int countP; //静态数据成员引用性说明 private: //私有数据成员 int X,Y; }; Point::Point(Point &p) { X=p.X; Y=p.Y; countP++; } int Point::countP=0; //静态数据成员定义性说明 void main() //主函数 { int *count=&Point::countP; //声明一个int型指针,指向类的静态成员 Point A(4,5); //声明对象A cout<<"Point A,"<<A.GetX()<<","<<A.GetY(); //直接通过指针访问静态数据成员 cout<<" Object id="<<*count<<endl; Point B(A); //声明对象B cout<<"Point B,"<<B.GetX() <<","<<B.GetY(); //直接通过指针访问静态数据成员 cout<<" Object id="<<*count<<endl; }
例:通过指针访问类的静态函数成员
#include <iostream> using namespace std; class Point //Point类声明 { public: //外部接口 //其它函数略 static void GetC() //静态函数成员 {cout<<" Object id="<<countP<<endl;} private: //私有数据成员 int X,Y; static int countP; //静态数据成员引用性说明 }; // 函数实现略 int Point::countP=0; //静态数据成员定义性说明 void main() //主函数 { void (*gc)()=Point::GetC; //指向函数的指针,指向类的静态成员函数 Point A(4,5); //声明对象A cout<<"Point A,"<<A.GetX()<<","<<A.GetY(); gc(); //输出对象序号,通过指针访问静态函数成员 Point B(A); //声明对象B cout<<"Point B,"<<B.GetX()<<","<<B.GetY(); gc(); //输出对象序号,通过指针访问静态函数成员 }
#include<iostream> using namespace std; class Point { public: Point(){ X=Y=0; cout<<"Default Constructor called.\n"; } Point(int xx,int yy){ X=xx; Y=yy ; cout<< "Constructor called.\n"; } ~Point(){ cout<<"Destructor called.\n"; } int GetX() {return X;} int GetY() {return Y;} void Move(int x,int y) { X=x; Y=y; } 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; //删除对象,自动调用析构函数 return 0; }
运行结果:
#include<iostream> using namespace std; class Point { public: Point(){ X=Y=0; cout<<"Default Constructor called.\n"; } Point(int xx,int yy){ X=xx; Y=yy ; cout<< "Constructor called.\n"; } ~Point(){ cout<<"Destructor called.\n"; } int GetX() {return X;} int GetY() {return Y;} void Move(int x,int y) { X=x; Y=y; } private: int X,Y; }; int main() { Point *Ptr=new Point[2]; //创建对象数组 Ptr[0].Move(5,10); //通过指针访问数组元素的成员 Ptr[1].Move(15,20); //通过指针访问数组元素的成员 cout<<"Deleting..."<<endl; delete[ ] Ptr; //删除整个对象数组 return 0; }
运行结果:
#include<iostream> using namespace std; class Point { //类的声明同例6-16 … }; class ArrayOfPoints { public: ArrayOfPoints(int n) { numberOfPoints=n; points=new Point[n]; } ~ArrayOfPoints() { cout<<"Deleting..."<<endl; numberOfPoints=0; delete[] points; } Point& Element(int n) { return points[n]; } private: Point *points; int numberOfPoints; }; void main() { int number; cout<<"Please enter the number of points:"; cin>>number; //创建对象数组 ArrayOfPoints points(number); //通过指针访问数组元素的成员 points.Element(0).Move(5,10); //通过指针访问数组元素的成员 points.Element(1).Move(15,20); }
运行结果如下:
#include<iostream> using namespace std; void main() { float (*cp)[9][8]; int i,j,k; cp = new float[8][9][8]; for (i=0; i<8; i++) for (j=0; j<9; j++) for (k=0; k<9; k++) *(*(*(cp+i)+j)+k)=i*100+j*10+k; //通过指针访问数组元素 for (i=0; i<8; i++) { for (j=0; j<9; j++) { for (k=0; k<8; k++) //将指针cp作为数组名使用, //通过数组名和下标访问数组元素 cout<<cp[i][j][k]<<" "; cout<<endl; } cout<<endl; } }
#include <iostream> #include <cassert> using namespace std; class Point { //类的声明同例6-16 … }; 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 points(count); //创建数组对象 points.element(0).move(5, 0); //访问数组元素的成员 points.element(1).move(15, 20); //访问数组元素的成员 return 0; }
为什么element函数返回对象的引用?
#include <iostream> #include <vector> using namespace std; //计算数组arr中元素的平均值 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 << "n = "; cin >> n; vector<double> arr(n); //创建数组对象 cout << "Please input " << n << " real numbers:" << endl; for (unsigned i = 0; i < n; i++)cin >> arr[i]; cout << "Average = " << average(arr) << endl; return 0; }
例:基于范围的for循环配合auto举例
#include <vector> #include <iostream> int main() { std::vector<int> v = {1,2,3}; for(auto i = v.begin(); i != v.end(); ++i) std::cout << *i << std::endl; for(auto e : v) std::cout << e << std::endl; }
#include<iostream> using namespace std; class Point { //类的声明同例6-16 //…… }; class ArrayOfPoints { //类的声明同例6-18 //…… }; void main() { int number; cin>>number; ArrayOfPoints pointsArray1(number); 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; }
运行结果如下:
#include<iostream> using namespace std; class Point { //类的声明同例6-16 …… }; class ArrayOfPoints { public: ArrayOfPoints(ArrayOfPoints& pointsArray); //其它成员同例6-18 }; ArrayOfPoints ::ArrayOfPoints (ArrayOfPoints& pointsArray) { numberOfPoints =pointsArray.numberOfPoints; points=new Point[numberOfPoints]; for (int i=0; i<numberOfPoints; i++) points[i].Move(pointsArray.Element(i).GetX(), pointsArray.Element(i).GetY()); } void main() { //同例6-20 }
程序的运行结果如下:
移动构造
什么时候该触发移动构造?
有可被利用的临时对象
移动构造函数:
class_name ( class_name && )
使用深层复制构造函数
返回时构造临时对象,动态分配将临时对象返回到主调函数,然后删除临时对象。
#include<iostream> using namespace std; class IntNum { public: IntNum(int x = 0) : xptr(new int(x)){ //构造函数 cout << "Calling constructor..." << endl; } IntNum(const IntNum & n) : xptr(new int(*n.xptr)){//复制构造函数 cout << "Calling copy constructor..." << endl; }; ~IntNum(){ //析构函数 delete xptr; cout << "Destructing..." << endl; } int getInt() { return *xptr; } private: int *xptr; }; //返回值为IntNum类对象 IntNum getNum() { IntNum a; return a; } int main() { cout<<getNum().getInt()<<endl; return 0; }
运行结果:
#include<iostream> using namespace std; class IntNum { public: IntNum(int x = 0) : xptr(new int(x)){ //构造函数 cout << "Calling constructor..." << endl; } IntNum(const IntNum & n) : xptr(new int(*n.xptr)){//复制构造函数 cout << "Calling copy constructor..." << endl; } IntNum(IntNum && n): xptr( n.xptr){ //移动构造函数 n.xptr = nullptr; cout << "Calling move constructor..." << endl; } ~IntNum(){ //析构函数 delete xptr; cout << "Destructing..." << endl; } private: int *xptr; }; //返回值为IntNum类对象 IntNum getNum() { IntNum a; return a; } int main() { cout << getNum().getInt() << endl; return 0; }
运行结果:
#include <string> #include <iostream> 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"; cout << "s1 is " << s1 << endl; 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; return 0; }
考虑:如何输入整行字符串?
#include <iostream> #include <string> using namespace std; int main() { for (int i = 0; i < 2; i++){ string city, state; getline(cin, city, ‘,‘); getline(cin, state); cout << "City:" << city << “ State:" << state << endl; } return 0; }
运行结果:
原文:https://www.cnblogs.com/alec7015/p/12445730.html