虽然这一章我们课没有学,也是最后一章,但是我觉得很重要所以就自己自学了,并且在mooc上,我还会系统的学习c++面向对象的程序设计。这里书上讲的很笼统,也很少,我主要学一下一些模板的使用
重载构造函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
//【例13.2】的程序:构造函数的使用 #include <iostream> using namespace std; class Sample2 { int value; public: Sample2() { value=0; } //构造函数 Sample2(int v) { value=v; } //重载构造函数 int getvalue() { return value; } void setvalue(int v) { value=v; } }; int main() { Sample2 a[10]={0,1,2,3,4,5,6,7,8,9},b[10]; cout << "输出a:" << endl; for (int i=0;i<10;i++) { cout << "a[" << i << "]=" << a[i].getvalue() << " "; if ((i+1)%5==0) //每输出5个元素换一行 cout << endl; } cout << "输出b:" << endl; for (int i=0;i<10;i++) { cout << "b[" << i << "]=" << b[i].getvalue() << " "; if ((i+1)%5==0) //每输出5个元素换一行 cout << endl; } return 1; } |
析构函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//【例13.3】的程序:析构函数的使用 #include <iostream> using namespace std; class Sample3 { int x,y; public: Sample3(int x1,int y1) //构造函数 { x=x1;y=y1; } ~Sample3() //析构函数 { cout << "调用析构函数." << endl; } void dispoint() { cout << "(" << x << "," << y << ")" << endl; } }; int main() { Sample3 a(12,6),*p=new Sample3(5,12); //对象指针指向创建的无名对象 cout << "First point=>"; a.dispoint(); cout << "Second point=>"; p->dispoint(); //delete p; return 1; } |
使用stl设计数据结构算法
我发现后面我要学的mooc正好有,所以就不看书上的了。