1)单继承的案例代码
#include<iostream>
using namespace std;
class A
{
public:
A(int a,int b,int c)
{
x = a;
y = b;
z = c;
}
public:
int x;
int y;
int z;
};
class B : public A
{
public:
B(int aa,int bb,int cc,int dd,int ee) : A(aa,bb,cc)
{
m = dd;
n = ee;
}
void printHandle(void)
{
cout<<x<<" "<<y<<" "<<z<<" "<<m<<" "<<n<<endl;
}
private:
int m;
int n;
};
int main(void)
{
B b(1,2,3,4,5);
b.printHandle();
return 0;
}
输出结果:
1 2 3 4 5
2)类的继承中,要明确构造函数的执行流程,如下图所示:
执行流程:
- 先执行基类的构造函数初始化;
- 再执行子对象的构造函数初始化;
- 再执行派生类的构造函数初始化;
- 析构相反,不再赘述;
3)多重继承时,如果需要同名的基类成员,需要显示调用,代码如下:
#include <iostream>
using namespace std;
class A
{
public:
int x;
void print() {cout<< "x: "<<x<<endl; }
};
class B
{
public:
int x;
void print() {cout<< "x: "<<x<<endl; }
};
class C : public A, public B
{
public:
int x;
void print() {cout<< "x: "<<x<<endl; }
};
int main(void)
{
C c;
c.x = 10; //默认给派生类赋值
c.print();//默认调用的是派生类函数
c.A::x = 20; //显示说明给类A赋值 //注意这样的写法
c.A::print();//显示调用类A的成员函数
return 0;
}
4)对虚基类与虚继承的构造函数初始化的一个心得,如下图所示:
5)最简单的模板函数代码,如下所示:
#include<iostream>
using namespace std;
template<typename T>
inline T fun(T a, T b) //内联函数的inline 写到函数最前面
{
T tmp = (a > b) ? a : b;
return tmp;
}
int main(void)
{
cout<<fun<int>(3,5)<<endl;
return 0;
}
- 最简单的类模块代码测试:
#include<iostream>
using namespace std;
template<class T>
class Calc
{
public:
Calc(T arg)
{
number = arg;
}
T fun(void)
{
return number;
}
private:
T number;
};
int main(void)
{
Calc<int> test1(5); //用类模板定义对象,注意书写格式
cout<<test1.fun()<<endl;
return 0;
}
7)提取运算符<< 和 插入运算符>>的函数重载,实现对象的输入和输出,如下代码:
#include<iostream>
#include<istream>
#include<ostream>
using namespace std;
class Test
{
public:
Test(int a, int b)
{
x = a;
y = b;
}
friend ostream& operator<<(ostream& out,Test& obj);
friend istream& operator>>(istream& in,Test& obj);
private:
int x;
int y;
};
ostream& operator<<(ostream& out,Test& obj) //左操作数是类istream的引用,右操作数是输出对象的引用;
{
out<<obj.x<<" "<<obj.y<<endl;
return out;
}
istream& operator>>(istream& in,Test& obj)
{
in>>obj.x>>obj.y;
return in;
}
int main(void)
{
Test t1(10,20);
cout<<t1<<endl; //可以直接操作对象进行输出,如果没有运算符重载,是不可以的
cin >> t1; //可以直接操作对象,对其进行插入,如果没有运算符重载,是不可以的
cout<<t1<<endl;
return 0;
}
8)文件流的操作,代码如下:
#include<iostream>
#include<fstream>
using namespace std;
//ios_base::out 参考对象是内存;把内存数据out(写)到文件中;
//ios_base::in 参考对象是内存;从文件中in(读)到内存中;
int main(void)
{
fstream f;
f.open("1.txt",ios_base::out); //ios_base::out 打开文件模式标记
f.write("hello world",10);
f.close();
return 0;
}
9)都有哪些流呢,总结如下:
iostream、istream、 ostream、fstream、ifstream、ofstream;
10)STL之stack的使用
stack主要是用作容器适配器的使用;
测试代码如下:
#include<iostream>
#include<stack>
#include<list>
using namespace std;
int main(void)
{
list<int> ll{1,2,3,4,5,6,7};
stack<int,list<int>> test(ll); //注意:第二个参数默认是双端队列 stack<T,Container=deque>
//vector、deque 和 list 主要是这个三个类模板可以用作双端队列
while(!test.empty())
{
cout<<test.top();
test.pop();
}
return 0;
}
输出结果:
7654321