您的位置:首页 > 编程语言 > C语言/C++

C++命名空间及类的多态与(纯)虚函数,静态链接/动态链接

2016-08-03 13:57 281 查看
一、 命名空间

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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息