C++命名空间及类的多态与(纯)虚函数,静态链接/动态链接
2016-08-03 13:57
281 查看
一、 命名空间
1. 形象表示:有两个人名字相同,但是属于不同的公司,如何辨别?这就需要声明是哪个公司的人了。
关键词: namespace
案列:
二、类的多态与虚函数
这里当类的多态发生在基类派生或者子类继承情况下,如果基类不是用虚函数的话,则基类指针指向子类的成员函数或者变量的时候,输出仍然是基类的情况。具体实例如下:
如果基类不是
编译的结果仍然是父类的函数score的输出情况,即
the score of this student is:
但是,如果基类采用的是
the score of goodstu is:
the score of bedstu is:
由此可见虚函数的作用,第一种情况没有用虚函数,即使指向的是子类,但是输出的也是父类情况。所以称之为早绑定/静态链接,后面的那种情况则称之为后期绑定/晚链接。
这里简要叙述一下纯虚函数,如果我们在基类中无法给出该函数的准确定义,而在基类中重新给出定义,则可以采用纯虚函数,命名规则为:
1. 形象表示:有两个人名字相同,但是属于不同的公司,如何辨别?这就需要声明是哪个公司的人了。
关键词: namespace
案列:
#include "stdio.h" #include "iostream" using namespace std; namespace A { int a; int b; void fun(int a, int b) { int c=a < b ? a : b; cout << c << endl; } } namespace B { int a; int b; void fun(int a, int b) { int c=a > b ? a : b; cout << c << endl; } } int main() { using namespace A; cout << "please input 2 numbers:" << endl; int a, b; cin >> a; cin >> b; fun(a, b); B::fun(a, b);//B空间 A::fun(a, b);//A空间 return 0; }
二、类的多态与虚函数
这里当类的多态发生在基类派生或者子类继承情况下,如果基类不是用虚函数的话,则基类指针指向子类的成员函数或者变量的时候,输出仍然是基类的情况。具体实例如下:
/*类的多态与虚函数,早绑定/静态链接与后期绑定/动态链接*/ #include "stdio.h" #include "iostream" using namespace std; //定义基类student class student { public: student(); ~student(); //这里如果不用虚函数,则为静态链接。 // int score() virtual int score() { cout << "the score of this student is:" << endl; return 0; } private: }; //定义子类,goodstu和bedstu,公有继承基类student class goodstu :public student { //重新定义基类函数score int score() { cout << "the score of good is:" << endl; return 0; } }; class bedstu : public student { //重新定义基类函数score int score() { cout << "the score of bed is:" << endl; return 0; } }; //主函数 int main() { //定义基类student类型的指针p //定义子类goodstu类型的xiaoming,bedstu类型的xiaohu student *p; goodstu xiaoming; bedstu xiaohu; //父类指针指向子类xiaoming p = &xiaoming; p->score(); //父类指针指向子类xiaohu p = &xiaohu; p->score(); return 0; } //构造函数和析构函数的定义 student::student() { } student::~student() { }
如果基类不是
virtural int student(){},则即使子类用
p = &xiaoming; xiaoming->score(); p = &xiaohu; xiaohu->score();
编译的结果仍然是父类的函数score的输出情况,即
the score of this student is:
但是,如果基类采用的是
virtual int student(),则子类的输出为:
the score of goodstu is:
the score of bedstu is:
由此可见虚函数的作用,第一种情况没有用虚函数,即使指向的是子类,但是输出的也是父类情况。所以称之为早绑定/静态链接,后面的那种情况则称之为后期绑定/晚链接。
这里简要叙述一下纯虚函数,如果我们在基类中无法给出该函数的准确定义,而在基类中重新给出定义,则可以采用纯虚函数,命名规则为:
virtual int student()=0;
相关文章推荐
- 初级C++3继承、多态、异常、命名空间
- 用示例学习C++的命名空间Namespaces
- C++ 虚函数 多态
- C++对象布局及多态实现之带虚函数的类
- c++ 多态 虚函数 析构函数 抽象类
- Effective C++ (4) c++中的命名空间
- C++ 第三篇 关于预处理器指示符和命名空间
- C++ 虚函数-多态的执行
- [VC++]C++中类的多态与虚函数的使用
- 读书笔记-Thinking in C++-第15章 多态和虚函数
- C++ 头文件和命名空间
- C++ 虚函数 多态
- C++中的命名空间
- C++ 虚函数 多态
- C++特性探寻-多态和虚函数
- C++虚函数和多态学习笔记
- C++中命名空间"std"名字由来的思考
- C++-namespace(命名空间)
- C++ 虚函数 多态
- c++的命名空间namespace的作用