类的大小:
1)一般情况下,类的大小是类里数据成员大小之和,普通函数不占空间;
2)static不占空间大小;
3)virtual虚函数,如果有虚函数,则多一个Vptr(虚指针),不管有多少虚函数,都只有一个虚指针,指针占4个字节大小。
4)空类占一个字节大小。
构造函数的运行顺序:
class Test
{
public:
Test(int data = 0) : m_data(data)
{
cout << “Creat Test Object:” << this << endl;
}
Test(const Test &t)
{
m_data = t.m_data;
cout << “Creat Copy Test Object:” << this << endl;
}
Test& operator=(const Test &t) //&引用提升效率, 1.不在开辟空间2.拷贝构造也不需要再调动赋值之类的
//Test& operator=(Test* const this, const Test &t)
{
cout << "Asign : " << this << “=” << &t << endl;
if (this == &t)
return *this;
m_data = t.m_data;
return *this;
}
~Test()
{
cout << “Free Test Object.” << this << endl;
}
public:
int GetValue()const
{
return m_data;
}
private:
int m_data;
};
Test fun(Test x) //2.传递对象t时,会有一次拷贝构造 //拿对象t初始化对象x;
//Test fun(Test &x) //构造,构造, 拷贝构造
//Test& fun(Test x) //会被警告,拿一个临时对象返回
{
int value = x.GetValue();
Test tmp(value);// 3.构造
//无法直接返回tmp;
return tmp; //4.拷贝构造; 构造一个无名的临时对象,用tmp初始化临时对象,
}
Test fun(Test &x)
{
int value = x.GetValue();
return Test(value);
}
int main()
{
Test t(100); //1,构造函数
//fun(t); //会有几次构造
//Test t2;
//t2 = fun(t); //构造t,构造t2, 拷贝构造x, 构造tmp, 拷贝构造临时对象,释放tmp,释放x 赋值语句
//Test t2 = fun(t); //构造t, 构造tmp, 拷贝构造临时对象,析构tmp, 拷贝构造t2,析构临时对象
//析构t2, 析构t;
//但是编译器会进行优化, 直接将t2,作为临时拷贝对象
return 0;
}