初始化类成员变量的方法,有两种,首先呢第一种
#include <iostream>
class Entity
{
private:
std::string m_Name;
public:
//初始化成员变量的方法
Entity()
{
m_Name = "Veyron_void";
}
Entity(const std::string& name)
{
m_Name = name;
}
void getname()
{
std::cout << m_Name << std::endl;
}
};
int main()
{
Entity e0;
Entity e1("Veyron_not_void");
e0.getname();
e1.getname();
std::cin.get();
}
输出:
Veyron_void
Veyron_not_void
第二种方法(初始化成员列表):
方法说明:http://c.biancheng.net/cpp/biancheng/view/2979.html
(不使用初始化列表创建完所有参数,想在以后补,或者在constructor内部写一个赋值的函数。这种思想不太好,会导致内存的浪费。下面的代码例子,创建一个Example的类,来明显的说明这个初始化的过程)
#include <iostream>
class Example
{
private:
int exa;
public:
//对构造函数进行重载处理,不传参的形式
Example()
{
std::cout << "You are creating a new Example without arg!!" << std::endl;
}
Example(int shuzi)
: exa(shuzi)
{
std::cout << "You are creating a new Example with arg:" << shuzi << std::endl;
}
};
class Entity
{
private:
std::string m_Name;
//实例化 Example类
Example exa1;
public:
int x, y, z;
//使用使用初始化参数列表,初始化各个类定义的参数
Entity()
: m_Name("Name_initial"), x(1) , y(2), z(3)
{
m_Name = "Veyron_void";//如果在初始化列表中没有初始化这个m_Name的参数,而是写在了内部那么:
// 这个m_Name 对象实际上被构建两次,第一次是默认的无参数形式,第二次是包含这个"Veyron_void"的string。然后一次创建两个string内存,比较不高效。
std::cout << "I am creating a new Entity!" << std::endl;
//调用函数初始化exa1的值,但是,这样的内部初始化一个变量,会导致重新创建一个对象的实体,再用一次构造器功能,相当于用了两次
//也就是初始化列表中没有创建的变量,将会导致之后创建是赋值机制,而不是默认创建。
exa1 = Example(11);
}
Entity(const std::string& name)
{
m_Name = name;
}
void getname()
{
std::cout << m_Name << std::endl;
}
};
int main()
{
Entity e0;
//Entity e1("Veyron_not_void");
e0.getname();
//e1.getname();
std::cout << e0.x << e0.y << e0.z << std::endl;
std::cin.get();
}
输出:
You are creating a new Example without arg!!
I am creating a new Entity!
You are creating a new Example with arg:11
Veyron_void
123