在C++语言中,如果定义一个全局变量或者静态变量(即创建在函数以外的或者有static关键字修饰的)没有赋初值,编译器就会执行默认初始化,默认初始化的值为零,如果定义一个局部变量(自动对象),初始化值为栈里的随机值。
以int类型为例,简单的赋值,没有什么好解释的
#include
using namespace std;
int main(){
int a=0;
return 0;
}
以string为例,通过调用标准库中string类的构造函数来初始化变量
#include
#include
using namespace std;
int main(){
string a("string");
return 0;
}
在定义vector对象的时候,要注意需要用圆括号还是大括号
#include
#include
int main(){
int val=0,n=10;//设置数值是为了通过编译
vector v1(n,val);//等价于v1中含有n个值为val的元素
vector v2(v1);//v2中包含有v1所有的元素副本
vector v3(n);//包含了n个执行了默认初始化的元素
vector v4{1,2,3,4,5};//类似于数组初始化
vector v5={1,2,3,4,5};//等价于v4
return 0;
}
以vector为例,通过传入一个数组的begin和end迭代器,将其所有的元素全部赋值给vector。array,string,deque等顺序容器也可以用这种方式来初始化。
#include
#include
#include
using namespace std;
int main(){
array a={1,3,5,7,9};
vector(a.begin(),a.end());
return 0;
}
在创建类的时候通常会创建一个与类同名的函数,名为构造函数。如下图所示:
#include
using namespace std;
class Person{
public:
Person()=default;
Person(int age,double h,double w) const {
this->age=age;//同名变量的相互赋值需要用this指针来区分
height=h;
weight=w;
}
inline int disage() const { //类内函数自动内联
return this->age;
}
private:
int age;
double height;
double weight;
};
int main(){
Person a(25,180,65);
cout<
这种方式其实是先创建好私有变量,再将其赋值,为了能够直接初始化,C++提供了列表初始化的语法,如下图所示:
#include
using namespace std;
class Person{
public:
Person()=default;
Person(int age,double h,double w) : age(age),weight(w),height(h)//列表初始化自动识别同名变量
{}
inline int disage() const { //类内函数自动内联
return this->age;
}
private:
int age;
double height;
double weight;
};
int main(){
Person a(25,180,65);
cout<
以上就是几种常见的初始化方法。初学者一定要切记初始化和赋值是两个概念,初始化是在创建这个变量的时候就已经有值存在,而赋值是用新值来覆盖掉原来的值。
不求关注,只求改正!