C++ Primer Plus第十二天
对类成员使用动态内存分配
静态变量:在类中声明了还要在外面定义一下
class 类名{
private:
static int number ;
};
int 类名::number = 0;
类的静态成员是共享类里面的
下面这个是重载<<操作符
std::ostream& operator<<(std::ostream& os, const StringBad& st)
{
os << st.str;
return os;
}//这句话特重要
类的赋值注意:
类名 C1 = C2;
此时会有:类名 C1 = 类名(C2);
类会自动生成的成员函数:
默认构造函数
class_name();
默认析构函数
~class_name();
复制构造函数
class_name(const Class_name &);
Myc c1(c2);
Myc c3 = c4;
Myc c5 = Myc(c6);
Myc *c7 = new Myc(c6);
默认的复制构造函数会浅层复制,然后会导致副本删除了之后,本体的地址也被delete[]了
赋值运算符
class_name & class_name::operator=(const class_name &);
class_name c2("hello world");
class_name c3;
c3 = c2;
而 class_name c3 = c2;可能不会用赋值运算符
地址运算符
C++11会提供另外两个:移动构造函数和移动赋值运算符
C++11表示的空指针:nullptr
const string answer("futile");//将调用下面符号重载
const char & String::operator[](int i) const
重载<<、>>符号
friend ostream & operator << (ostream & os,const class_name & st);
friend istream & operator >> (istream & is,class_name & st);
istream & operator >> (istream & is,class_name & st)
{
char temp[class_name::CINLIM];
is.get(temp,class_name::CINLIM);
if(is)
st = temp;
while(is && is.get() != '\n')
continue;
return is;
}
隐式和显示复制构造函数
隐式和显示重载赋值运算符
在构造函数中使用new所必须完成的工作
使用静态类成员
静态成员函数只能访问静态成员
静态成员函数是针对全体的,所以调用的时候不能用this
例如:
int number = calss_name :: return_static();
将定位new运算用于对象
声明指向类对象的指针:string * glamour;
将指针初始化为已有的对象:string * first = &saying [0]
使用new和默认的类构造函数对指针进行初始化:string *p = new string;
使用new和string(const char *)类构造函数对指针进行初始化:
string * p = new string("my my my")
使用new和string(const string&)string *p = new string (saying [choice])
使用->操作符通过指针访问类方法:
if(saying[i].length() < short->length())
*解引用
定位new:
不能用delete;
需要手动:p->~class_name();