1.访问控制
C++访问控制符有三个private、protected、public。
一个类友元(包含友元函数或者友元类的成员函数或者友元类的所有成员函数)可以访问该类的任何成员(包括成员变量及成员方法)。
除去友元外,private成员只有该类自身的成员函数可以访问,protected成员只有该类及其派生类的成员函数可以访问,public成员则该类及其派生类的成员函数和对象都可以访问。
类的继承方式有三种:private、protected、public。
1)private属性不能被继承。
2)使用private继承,父类的protected和public属性在子类中变为private;
使用protected继承,父类的protected和public属性在子类中变为protected;
使用public继承,父类中的protected和public属性不发生改变;
2.成员变量初始化
const数据成员必须在构造函数的初始化列表中初始化
static数据成员必须在内的外部进行初始化
const static数据成员必须在申明的时候就进行初始化
初始化列表中的初始化顺序最好是按照变量的申明顺序进行初始化
3.拷贝构造函数 赋值构造函数
拷贝构造函数是在对象被创建时调用的,而赋值函数只能被已经存在了的对象调用。
String a(“hello”);
String b(“world”);
String c = a; // 调用了拷贝构造函数,最好写成 c(a);类String 的拷贝构造函数与赋值函数
// 拷贝构造函数
String::String(const String &other)
{
// 允许操作other 的私有成员m_data
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data);
}
// 赋值函数
String & String::operator =(const String &other)
{
// (1) 检查自赋值
if(this == &other)
return *this;
// (2) 释放原有的内存资源
delete [] m_data;
// (3)分配新的内存资源,并复制内容
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data);
// (4)返回本对象的引用
return *this;}