一、继承和派生
1、面向对象的三大特征:封装、继承、多态。
封装:将数据类型和接口组合在一起,根据需要提供外界对其访问的权利。
继承:在一个已存在的类的基础上建立一个新的类,新的类可以从已有的类那里获得其已有的特性,而自己又可以有自己特定的数据和行为,符合可重用编程思想。
多态:多态即一个名字,多种方法,比如C++的虚函数、重载函数都是多态的表现。
2、派生类继承了基类的所有数据成员和成员函数(除了构造函数和析构函数),并可以对成员做必要的增加。
可以在派生类中声明一个与基类成员同名的成员,此时,派生类中的成员会覆盖基类的成员。
类中的成员分为public公用成员、protected保护成员、private私有成员:
public公用成员能在类外、类中成员函数、派生类中成员函数中调用。
protected保护成员可以在类中成员函数、派生类中成员函数中调用。
private私有成员只能被本类中成员函数调用。
继承方式包括public、private、protected,如果没有指定的话默认为private继承方式:
公用继承public:基类的公用成员、保护成员、私有成员在派生类对象中保持原有的访问属性,所以派生类中可以访问基类的公共成员和保护成员,通过派生类对象可以访问基类的公共成员。
保护继承protected:基类的公用成员、保护成员在派生类中成了保护成员,私有成员仍为私有成员,所以派生类中可以访问基类的公共成员和保护成员,通过派生类对象不能访问基类的公共成员。
私有继承private:基类的公用成员、保护成员、私有成员在派生类对象中成都变成了私有成员,所以派生类中不可以访问基类的公共成员和保护成员,通过派生类对象不能访问基类的公共成员。
3、普通派生类的构造函数:
基类的初始化工作也要由派生类的构造函数来完成,方法就是在派生类的构造函数中调用基类的构造函数,构造函数的调用顺序为先调用基类的构造函数再调用派生类的构造函数。
基类的析构函数同样不能被派生类继承,但在执行派生类的析构函数中会自动执行基类的析构函数,所以是先调用派生类的析构函数再调用基类的析构函数。
class animal
{
public:
animal(int h=0, int w=0):height(h),weight(w){}//基类的构造函数
~animal(){}
void display_animal();
private:
int height;
int weight;
};
void animal::display_animal()
{
cout << "height:" << height << endl;
cout << "weight:" << weight << endl;
}
animal::~animal()
{
cout << "animal destructor" << endl;
}
class person:public animal
{
public:
person(int h, int w, string nam):animal(h, w),name(nam){}//普通派生类的构造函数,方式1
//person(int h, int w, string nam):animal(h, w){ name = nam;}//普通派生类的构造函数,方式2
~person(){}
void display_person();
private:
string name;
};
void person::display_person()
{
display_animal();//派生类继承了基类的成员函数
cout << "name:" << name << endl;
}
person::~person()
{
cout << "person destructor" << endl;
}
包含对象数据成员的派生类的构造函数:
包含对象数据成员的派生类的构造函数包括三方面内容,一是调用基类的构造函数,二是对对象数据成员初始化,三是对派生类数据成员的初始化,所以构造函数的执行顺序为先执行基类的构造函数,再执行对象数据成员的构造函数,最后执行派生类的构造函数。
class plant
{
public:
plant(string col):color(col){}
~plant(){}
void display_plant();
private:
string color;
};
void plant::display_plant()
{
cout << "color:" << color << endl;
}
plant::~plant()
{
cout << "plant destructor " << endl;
}
class tree:public plant
{
public:
tree(string col, int a):plant(col),belong(col),age(a){}//包含对象数据成员的派生类的构造函数
~tree(){}
void display_tree();
private:
plant belong;
int age;
};
void tree::display_tree()
{
display_plant();
cout << "belong plant of color:";
belong.display_plant();
cout << "age:" << age << endl;
}
tree::~tree()
{
cout << "tree destructor" << endl;
}
多层派生时的构造函数:
经多层派生的派生类,其构造函数只需包含上一层基类的构造函数的调用和派生类自己成员的初始化即可。构造函数的执行顺序为先调用最上层基类的构造函数,再调用中间基类的构造函数,最后调用派生类的构造函数。
class animal
{
public:
animal(int h=0, int w=0):height(h),weight(w){}
~animal(){}
void display_animal();
private:
int height;
int weight;
};
class person:public animal
{
public:
person(int h, int w, string nam):animal(h, w),name(nam){}
~person(){}
void display_person();
private:
string name;
};
class man:public person
{
public:
man(int h, int w, string nam, string s):person(h, w, nam),sex(s){}//多层继承时的构造函数
~man(){}
void display_man();
private:
string sex;
};
void animal::display_animal()
{
cout << "height:" << height << endl;
cout << "weight:" << weight << endl;
}
void person::display_person()
{
display_animal();
cout << "name:" << name << endl;
}
void man::display_man()
{
display_person();
cout << "sex:" << sex << endl;
}
多重继承时的构造函数:
多重继承而来的派生类的构造函数只需包含多个基类的构造函数的调用和自己成员的初始化即可,构造函数的调用顺序是按照声明派生类时基类的出现顺序决定的。
class plant
{
public:
plant(string col):color(col){}
~plant(){}
void display_plant();
private:
string color;
};
class animal
{
public:
animal(int h=0, int w=0):height(h),weight(w){}
~animal(){}
void display_animal();
private:
int height;
int weight;
};
class plant_animal:public plant,public animal
{
public:
plant_animal(string col, int height, int weight, string foo):plant(col),animal(height, weight),food(foo){}//多重继承时的构造函数
~plant_animal(){}
void display_plant_animal();
private:
string food;
};
void plant::display_plant()
{
cout << "color:" << color << endl;
}
void animal::display_animal()
{
cout << "height:" << height << endl;
cout << "weight:" << weight << endl;
}
void plant_animal::display_plant_animal()
{
display_plant();
display_animal();
cout << "food:" << food << endl;
}
当不需要对派生类中的成员进行初始化的时候,派生类的构造函数的函数体可以为空:
......
person(int h, int w):animal(h, w){}
......
如果在基类中没有定义构造函数,或者基类中只定义了没有参数的构造函数,则派生类的构造函数中可以不再调用基类的构造函数,因为此时系统会自动调用基类的默认构造函数。
4、多重继承带来的二义性问题:
如果两个基类A和B有同名数据成员a(public属性)、成员函数display();甚至派生类C中也包含这些同名成员;或者两个基类从同一个类中派生(类A和类B必然有同名数据成员);这三种情况下派生类C的对象要访问同名成员的时候要加上基类名和作用域符号,如:
C c1;
c1.A::a = 3;
c2.B::display();
如果不加基类名和作用域符号的话默认引用的是派生类中的成员,如:
C c1;
c1.A = 3;
c1.display();
虚基类可以解决上面的第三种情况带来的二义性问题,使最后的派生类C只保留一份同名数据,virtual用来声明虚继承,如:
class N
{
...
};
class A:virtual public N //声明N是A的虚基类
{
......
};
class B:virtual public N//声明N是B的虚基类
{
......
};
class C:public A, public B
{
......
};
而此时最后的派生类的构造函数也与以往有所不同:不仅要负责对两个基类进行初始化,还应加上虚基类的初始化。
而且应该通过构造函数的初始化表进行初始化工作,如:
class person
{
public:
person(string nam, char s, int a):name(nam),sex(s),age(a){}
~person(){}
protected:
string name;
char sex;
int age;
};
class student:virtual public person//声明person为虚基类
{
public:
student(string nam, char s, int a, int sco):person(nam, s, a),score(sco){}
~student(){}
protected:
int score;
};
class teacher:virtual public person//声明person为虚基类
{
public:
teacher(string nam, char s, int a, string tit):person(nam, s, a),title(tit){}
~teacher(){}
protected:
string title;
};
class graduate:public student,public teacher//虚基类的间接派生类的构造函数
{
public:
graduate(string nam, char s, int a, int sco, string tit, int w):
person(nam, s, a),student(nam, s, a, sco),teacher(nam, s, a, tit),wages(w){}
~graduate(){}
void display_graduage();
private:
int wages;
};
void graduate::display_graduage()
{
cout << "name:" << name << endl;
cout << "sex:" << sex << endl;
cout << "age:" << age << endl;
cout << "score:" << score << endl;
cout << "title:" << title << endl;
cout << "wages:" << wages << endl;
}
5、可以将派生类对象赋给基类对象,在赋值时,派生类舍去自己的成员。
指向基类的指针可以指向派生类对象,而通过指向基类的指针不能访问派生类的成员,除非使用虚函数才能访问派生类中与基类同名的函数。
6、一般情况下我们会将类的构造函数和析构函数声明为public,但也会有一些特殊情况,比如:
①、我们想要实现单例模式,那么就可以将类的构造函数声明为private,使调用者不能自己定义该类的对象:
class CSingleton
{
public:
static CSingleton* getInstance()
{
if (nullptr == m_pInstance)
{
std::lock_guard<std::mutex> mu(m_mutex);
if (nullptr == m_pInstance) //使用双重检测,避免每次getInstance()都加锁
m_pInstance = std::unique_ptr<CSingleton>(new CSingleton);
}
return m_pInstance.get();
}
CSingleton(const CSingleton&) = delete;
CSingleton& operator=(const CSingleton&) = delete;
private:
CSingleton() {}
static std::mutex m_mutex;
static std::unique_ptr<CSingleton> m_pInstance;
};
std::mutex CSingleton::m_mutex;
std::unique_ptr<CSingleton> CSingleton::m_pInstance;
②、对于一个类如果我们不想调用者定义该类的对象,那么我们还可以将它的析构函数声明为protected,使析构函数只能在本类或派生类中被调用,不能在类外对它进行释放,从而达到不能定义该类的对象的目的,如下所示。当然,一般情况下我们都是声明一个抽象类来实现该类的对象不能被定义,这个抽象类只是用来做基类来派生派生类的。
class CAbstract
{
public:
CAbstract(){}
protected:
virtual ~CAbstract(){}
};
二、多态性与虚函数
1、虚函数的作用是可以通过基类指针来访问派生类中同名函数。
虚函数的使用方法是在基类的同名函数声明中加上virtual关键字,定义时不必再加上。
C++规定当一个成员函数被声明为虚函数后,其派生类中的同名函数会自动成为虚函数,因此派生类中同名函数的声明中可以加virtual或者override, 也可以不加。
虚函数不能在父类的构造函数中调用,因为此时调用的永远是父类的虚函数。
class Student
{
public:
Student(int n, string nam, float s):num(n), name(nam), score(s){}
virtual void display()
protected:
int num;
string name;
float score;
};
class Graduate:public Student
{
public:
Graduate(int n, string nam, float s, float p):Student(n, nam, s),pay(p){}
virtual void display();
private:
float pay;
};
void Student::display()
{
cout << num << "," << name << "," << score << endl;
}
void Graduate::display()
{
cout << num << "," << name << "," << score << "," << pay << endl;
}
Graduate grad1(1001, "Li", 94.5, 1500);
Student *pt = &grad1;
pt->display();//输出为1001, Li, 94.5, 1500
(在编程中发现以上代码中两个类的声明和实现的代码都在一个头文件中的话则编译会通不过,暂时不知原因- -!)
使用虚函数使系统增加一定的空间开销,因为当一个类中带有虚函数时,编译系统会为该类构造一个虚函数表,它是一个指针数组,存放每个虚函数的入口地址。
2、以下函数不能声明为虚函数:构造函数、内置函数、非类的成员函数、静态成员函数。
2、基类的析构函数我们一般都是将其声明为虚函数,这样该类的所有派生类的析构函数会自动成为虚函数。将类的析构函数声明为虚函数的原因是:用基类指针指向new开辟的派生类对象时,在对基类指针delete后,不会调用派生类的析构函数,解决方法就是将顶层基类的析构函数声明为虚函数。
4、有时候在基类中将某个成员函数声明为虚函数,并不是基类的要求,而是考虑到派生类的需要,在基类中预留一个函数名,具体功能留给派生类去定义,这种情况下应将基类中的这个成员函数声明为纯虚函数,声明纯虚函数的方法为先将函数声明为虚函数,然后在函数声明的后面加上"const = 0",纯虚函数无函数体,不需定义,如:
......
virtual float area() const = 0;
......
纯虚函数不能被调用,无函数体,它只是告诉编译器在这里声明一个虚函数,留待派生类根据需要对其定义。而如果派生类中没有对该虚函数进行定义,那么该虚函数在派生类中仍为纯虚函数。
5、在C++中有一些类,它们不是用来定义对象的,而是作为基类用来建立派生类,使用这些派生类再去定义对象。这种不用来定义对象而只作为基类来派生派生类的类成为“抽象类”或“抽象基类”。
凡是包含纯虚函数的类都是抽象类,如果抽象类的派生类对所有的纯虚函数进行了定义,那么这个派生类就不再是抽象类。
三、IO操作

1、流IO
istream和ostream类中分别重载了运算符>>和<<来对指定对象进行IO操作(如下所示),cin、wcin就是istream、wistream类型的对象,其指向标准输入stdin,wcout、wcerr是ostream、wostream类型的对象,其指向标准输出stdout和标准出错stderr。
class ostream
{
public:
ostream& operator<< (int val)
{
......
return *this;
}
ostream& operator<< (char* str)
{
......
return *this;
}
......
};
因为ostream类中没有重载自定义类型<<(CustomType),所以不能使用cout<<来输出我们自定义类型的对象,我们可以自己来添加一个重载方法来实现cout输出自定义类型对象:
class CFoo
{
public:
friend std::ostream& operator<<(std::ostream& out, CFoo& foo);
private:
int m_iNum{ 100 };
};
std::ostream& operator<<(std::ostream& out, CFoo& foo)
{
out << foo.m_iNum;
return out;
}
int main()
{
CFoo foo;
std::cout << foo; //输出 100
return 0;
}
如下为重定向cin到文件的示例:
std::ifstream fin;
fin.open("input.txt"); //input.text文件内容为: "hello world!"
std::streambuf * backup = std::cin.rdbuf(); //备份
std::cin.rdbuf(fin.rdbuf()); //重定向
std::string str;
std::cin >> str;
std::cout << str << std::endl; //输出为 hello world!
fin.close();
std::cin.rdbuf(backup); //恢复
如下为cout的格式输出控制:
cout << 1.1 << endl; //输出为 1.1
cout << 1.23456789 << endl; //输出为 1.23457(默认浮点数显示位数为6位)
cout.precision(8); //设置显示位数为8位
cout << 1.23456789 << endl; //输出为 1.2345679
//如果需要单独设置小数位的输出位数需要先通过fixed设置定点计数法显示(scientific为科学计数法显示)
std::cout << std::fixed; //定点计数法显示
cout.precision(3); //设置显示3位小数
std::cout << 1.23456 << std::endl; // 输出 1.235
cout << std::hex; //设置16进制显示
cout << 15; //输出为f
cout.width(8); //设置字符显示宽度(右对齐)
cout.fill('*'); //填充未被使用的部分(默认使用空格填充)
cout << "test"; //输出为: ****test
cout << std::setprecision(4) << std::setw(10) << std::setfill('*') << 1.23456789; //precision + width + fill,需要头文件<iomanip>,输出为 "*****1.235"
std::ios_base::fmtflags backup = cout.setf(std::ios_base::showpoint | std::ios_base::showpos); //显示末尾的小数,正数前显示+
cout << 1.2; //输出为1.20000
cout.setf(std::ios_base::showbase | std::ios_base::uppercase); //对于16进制显示时,添加0x标志,设置字母大写
cout << std::hex;
cout << 15; //输出为0XF
cout.setf(std::ios_base::scientific, std::ios_base::floatfield); //使用科学计数法显示,对于科学计数法显示的显示精度指的是小数位数而不是总位数
cout << 1.2345678; //输出为1.234568e+00
cout.setf(backup); //还原
2、文件IO
标准输入和输出使用的是行缓存,而文件IO使用的是全缓存,只有当缓冲区已满或者调用flush()方法或者关闭IO对象的时候数据才会写入文件。
/******************写文件*******************/
//文件不存在就创建,存在清空该文件
//std::ofstream outFile("ttt.txt", ofstream::binary);
//文件不存在就创建,存在打开成功
/*std::ofstream outFile("ttt.txt", std::ofstream::binary | ios::in);
if (!outFile)
outFile.open("ttt.txt", ofstream::binary);*/
//文件不存在就创建,存在移动写指针到文件末尾,并且每次写都是从文件末尾写(写操作之前会先移动写指针到文件末尾)
//std::ofstream outFile("ttt.txt", std::ofstream::binary | ios::app);
//文件不存在就创建,存在移动写指针到文件末尾
/*std::ofstream outFile("ttt.txt", std::ofstream::binary | ios::in);
if(outFile)
outFile.seekp(0, outFile.end);
else
outFile.open("ttt.txt", ofstream::binary);*/
//文件不存在失败,存在打开成功
//std::ofstream outFile("ttt.txt", std::ofstream::binary | ios::in);
//文件不存在失败,存在移动写指针到文件末尾
//std::ofstream outFile("ttt.txt", std::ofstream::binary | ios::in | ios::ate);
/******************读文件*******************/
//文件不存在打开失败,存在打开成功
//std::ifstream inFile("ttt.txt", std::ofstream::binary);
//文件不存在打开失败,存在移动读指针到文件末尾
//std::ifstream inFile("ttt.txt", std::ofstream::binary | ios::ate);
//文件不存在创建文件,存在打开成功
/*std::fstream File("ttt.txt", ios::in | std::ofstream::binary);
if (!File)
{
File.open("ttt.txt", std::ofstream::binary | ios::out);
File.close();
}*/
std::fstream file("data.dat", std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::app); //打开文件进行读写,文件不存在就创建,app指定每次写从文件末尾开始(stream对象析构时自动调用成员close关闭文件)
if (file)
{
//seekg()移动读(get)指针,seekp()移动写(put)指针,tellg()获得当前读位置,teellp()获得当前写位置
//seekg(绝对位置),seekg(相对位置, 参照位置):“相对位置”为正数的话是向后移动, 负数向前移动,“参照位置”有ios::beg、ios::cur、ios::end
/********获得文件大小********/
file.seekg(0, file.end); //移动读位置到文件末尾
int fileSize = file.tellg(); //tellg()获得当前读位置,也就获得了文件大小
file.seekg(0, file.beg); //恢复读位置到文件头
cout << "file size : " << fileSize << endl;
/********向文件写********/
std::streampos posPut = file.tellp(); //使用fstream进行读写的话使用的是同一个读写标记,所以应该在写之前保存读位置(读取的时候恢复),在读之前保存写位置(写的时候恢复)
file.write("123", 3);
file << "4567";
/********从文件读********/
file.seekg(posPut); //在读之前恢复原来的读位置
do {
char buf[4] = { 0 };
file.read(buf, 3);
if (file.gcount() > 0) ///获得读取的字符个数
cout << buf << endl;
} while (file);
if (file.eof()) //到文件末尾
cout << "file end" << endl;
}
使用fstream有时会出现问题,如下所示代码如果不使用seekp()那条语句的话write()方法并没有起作用,所以不推荐使用fstream:
std::fstream file("data.dat", std::fstream::in | std::fstream::out | std::fstream::binary | std::fstream::app);
if (file)
{
char buf[2] = { 0 };
file.read(buf, 1);
//file.seekp(0, file.end);
file.write("d", 1);
file.close();
}
以下为使用ifstream读取文件一行一行内容的代码,其实geline方法是以'\n'为分隔符来读取文件内容,还可以传入一个字符来使用指定的分隔符,推荐使用std中的getline方法来代替它,因为它允许使用string。
std::ifstream fileStream("data.dat", std::ifstream::in);
char buf[100] = {0};
while (fileStream.getline(buf, 100, '*'))
{
cout << buf << endl;
memset(buf, 0, sizeof(buf));
}
写入文件内容的时候需要一些注意的地方,如下所示:
std::wofstream file = std::wofstream("data.dat", std::ofstream::binary | std::ofstream::app);
int n = sizeof(L"abc"); //8,而不是6
file1.write(L"abc", sizeof(L"abc")); //会将最后的'\0'写进入,写入后文件大小为8
n = wcslen(L"abc"); //3
file2.write(L"abc", wcslen(L"abc") * sizeof(wchar_t)); //不会将最后的'\0'写进去,写入后文件大小为6
file3 << L"abc"; //不会将最后的'\0'写进入,写入后文件大小为3字节
std::wstring ws(L"abc");
n = ws.length(); //3,而不是6
3、string对象IO
以下是使用stringstream来进行字符串和数值之间的转换的例子,需要注意的是多次使用ostringstream对象来进行转换的话需要调用clear()和str("")成员方法来清空标志和缓存:
stringstream strStream;
char *p = "123456";
int i;
strStream << p;
strStream >> i;//i为123456
strStream.clear();
strStream.str("");
int num = 123456;
string str;
strStream << num;
strStream >> str;//str为"123456"
以下为使用ostringstream来将其他类型转换为string的方法,可以看到小数会进行四舍五入(同sprintf_s()),如果不希望四舍五入的话可以使用boost的lexical_cast(boost-字符文本处理 - 整鬼专家 - 博客园):
template<class T>
void to_string(std::string & result, const T& t, int prec = 0/*小数显示位数*/)
{
std::ostringstream oss;
oss << std::fixed; //不使用科学计数法
oss.precision(prec); //小数位数
oss << t;
result = oss.str();
}
std::string str;
to_string(str, 29999.999, 3); // str为"29999.999"
to_string(str, 29999.999, 2); // str为"30000.00"
to_string(str, 29999.999, 1); // str为"30000.0"
如下为使用stringstream来将数字转换为千分制:
std::string toThousands(int value, int dec = 0)
{
std::stringstream sstream;
sstream.imbue(std::locale(""));
sstream.precision(dec);
sstream << std::fixed << value;
return sstream.str();
}
int main()
{
std::cout << toThousands(12345678); //输出为 12,345,678
}
1926




被折叠的 条评论
为什么被折叠?



