类和对象3
一、初始化列表
1、狭义初始化
在定义变量的时候直接进行初始化,int i=3;
2,广义初始化
第一次给变量赋值就叫做初始化的情况叫广义初始化
int a;
...//跟a无关的代码
a=3;
初始化列表相当于狭义初始化,而构造函数内部相当于广义初始化
所以初始化列表可以解决一些只能用狭义初始化进行初始化的变量,例如:
1、const变量
2、引用
3、没有无参构造的类的对象
explicit 阻止单参构造的不规范调用
单参数的构造函数,可以用=直接调用,例如:假设CT类中有一个单参数的构造函数,参数类型为int或int相关类型, 那么,“CT a=3;”这种写法就是被允许的,但是这种写法十分别扭,看上去好像直接把3赋给了a, 为了避免这种写法,可以在构造函数加 explicit,使得这样的写法变得有效。
#include<iostream>
using namespace std;
class Test2{
public:
int b;
explicit Test2(int a) :b(a)
{}
Test2(Test2 & t)
{
b = t.b;
}
};
class Test
{
public:
int a = 5;
const int i=3;
int &ri;
//auto 不行
Test2 t2;
Test(int &a) :i(3), ri(a),t2(a)//相当于初始化
{}
};
int main1()
{
int i = 8;
int j = 9;
Test2 a(i);
Test2 b = a;
Test2 c(j);
cout << a.b << endl;//8
cout << c.b << endl;//9
system("pause");
return 0;
}
二、赋值运算符重载
operator=
运算符重载:
将运算符看成函数,把它的几目当成参数,通过参数的类型识别出对应的操作方法,相当于函数重载。
运算符重载有指定的规则,规则根据运算符来制定。
类会自动提供一个赋值运算符的重载(4),执行的是浅拷贝,跟拷贝构造相同
三、const成员函数
const加在成员函数的末尾,代表这个函数中的this是const修饰的
如果一个对象是const对象,那么它不能调用非const的成员函数
四、取地址运算符重载
类会自动提供两个取地址运算符重载,一个是针对普通对象的(5),一个是针对const对象的(6)
#include<iostream>
using namespace std;
class Testtop{
public:
int m_a;
int m_b;
Testtop() :
m_a(0),
m_b(0)
{
}
Testtop(int a, int b):
m_a(a),
m_b(b)
{
}
void test1(int a, int b)
{
test2(2, 4);
}
void test2(int a, int b) const
{
//test1(2, 4);
}
Testtop operator+(const Testtop &s) const
{
Testtop res;
res.m_a = m_a + s.m_a;
res.m_b = m_b + s.m_b;
return res;
}
Testtop & operator =(const Testtop & s)
{
m_a = s.m_a;
m_b = s.m_b;
return *this;
}
};
int main2()
{
Testtop a(3, 5);
Testtop b(2, 7);
Testtop c;
const Testtop d;
c = c = a + b;
cout << c.m_a << ' ' << c.m_b << endl;//5 12
system("pause");
return 0;
}
五、静态成员
静态成员跟类走不跟对象走,类在他在,而一般成员是对象在他才在。所以静态成员可以通过类名直接调用,而普通成员必须通过对象调用。
静态成员也有 private, public, protected之分
1、静态成员变量
1、所有对象共享,无论谁改了,所有的一起改
2、存储在全局区,不占用类的空间,所以取sizeof 的时候不算在内
3、赋初值只能在类外,赋值时不加 static, 用“类型 类名:: 变量名 = n " 直接赋值
2、静态成员函数
静态成员函数没有this指针,不能访问普通成员变量,但可以访问静态成员变量可以访问自己私有
静态成员函数不可以调用非静态成员函数
非静态成员函数可以调用类的静态成员函数
#include<iostream>
using namespace std;
class TestSt{
public:
int a;
static int m_s_i;
TestSt()
{
m_s_i++;
}
static void testst()
{
m_s_i = 4;
}
};
int TestSt::m_s_i = 0;
int main()
{
/* t1;
cout << t1.m_s_i << endl;//1
TestSt t2;
cout << t1.m_s_i << endl;//2
cout << t2.m_s_i << endl;//2
TestSt t3;
cout << t1.m_s_i << endl;//3
cout << t2.m_s_i << endl;//3
cout << t3.m_s_i << endl;//3
*/
TestSt::testst();
cout << TestSt::m_s_i << endl;//4
system("pause");
return 0;
}