#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class A {
private:
int number;
string name;
public:
// 缺省构造函数
A() :number(0), name("未知"){
cout << "调用缺省构造函数" << endl;
}
// 含参构造函数
A(int number,string name): name(name),number(number){
cout << "调用含参构造函数->" << number << " " << name << endl;
}
};
void static sum(int a[][3], int nRow) {
int sum = 0;
for (int i = 0; i < nRow; i++) {
for (int j = 0; j < 3; j++) {
sum += a[i][j];
}
}
cout << "Sum = " << sum << endl;
}
int main() {
//6_1.cpp
int a[10], b[10];
//初始化
for (int i = 0; i < 10; i++) {
a[i] = i * 2 - 1;
b[10 - i - 1] = a[i];
}
//范围for循环
for (const auto& e : a) {
cout << e << " ";
}
cout << endl;
//下标迭代循环
for (int i = 0; i < 10; i++) {
cout << b[i] << " ";
}
cout << endl;
cout << "--------1--------" << endl;
//声明数组
int c[3] = { 1,2,3 };
int d[] = { 1,2,3 };
//可以只给部分元素赋值,剩下自动赋值为0,不能间隔赋值
double e[5] = { 2.23,3.79,4.09 };
//注意:setprecision必须要和fixed或者scientific一起使用才能正确格式化输出
for (const auto& i : e) {
cout << fixed << setprecision(1) << i << endl;
//自动四舍五入
}
//第一维下标可以不用给出
int f[][3] = { 1,0,0,0,1,0 };
int g[2][3] = { {1,0,0},{0,1,0} }; //两者等价
//常量数组(必须给定初值)
const float fa[5] = { 1.0,2.0,3.0 };
cout << "--------2--------" << endl;
//把数组作为函数参数时,一般不指定数组第一维度大小,一般在第二个参数中给出
sum(g, 2);
cout << "--------3--------" << endl;
//对象数组(初始化是和调用类对应的构造函数形式格式一致)
A one[2] = { A(1,"李华"),A(2,"王明")};
A two[2] = { A(3,"李明") };
return 0;
}
-1 1 3 5 7 9 11 13 15 17
17 15 13 11 9 7 5 3 1 -1
--------1--------
2.2
3.8
4.1
0.0
0.0
--------2--------
Sum = 2
--------3--------
调用含参构造函数->1 李华
调用含参构造函数->2 王明
调用含参构造函数->3 李明
调用缺省构造函数