C语言参数类型不一致怎么办,C语言 具有不同参数类型的虚函数

我试图理解虚函数是如何工作的,我陷入了某个角色.

我写过这个小程序:

class First

{

public:

Virtual void f(int a)

{

cout << "First!" << endl;

cout << a << endl;

}

};

class Second : public First

{

public:

void f(int a) {

cout << "Second!" << endl;

cout << a << endl;

}

};

void main() {

Second s;

First *p = &s;

p->f(5);

First n;

p = &n;

p->f(3);

_getch();

}

此代码导致:

Second!

5

First!

3

但是,如果我将Second :: f()函数中的int更改为其他类型,如下所示:

class First

{

public:

Virtual void f(int a) {

cout << "First!" << endl;

cout << a << endl;

}

};

class Second : public First

{

public:

void f(double a) { //double instead int here!

cout << "Second!" << endl;

cout << a << endl;

}

};

void main() {

Second s;

First *p = &s;

p->f(5);

First n;

p = &n;

p->f(3);

_getch();

}

我的程序从不调用Second :: f(),我得到的结果如下:

First!

5

First!

3

有人可以向我解释为什么会这样吗?

当使用虚函数调度时,所谓的“最终覆盖”就是被调用的东西.对于甚至覆盖继承的虚函数的函数,它必须满足一些条件:

If a Virtual member function vf is declared in a class Base and in a

class Derived, derived directly or indirectly from Base, a member

function vf with the same name, parameter-type-list (8.3.5),

cv-qualification, and refqualifier (or absence of same) as Base::vf is

declared, then Derived::vf is also Virtual (whether or not it is so

declared) and it overrides Base::vf.

– ISO / IEC 14882:2001(E)§10.3(大胆强调我的)

很简单,在你的第二个例子中,Second :: f(double)的参数列表与First :: f(int)的参数列表不同,所以Second :: f(double)不是(自动)虚拟的并且不会覆盖First: :F(INT).

C 11关键字覆盖声明了一个方法覆盖继承的虚方法的意图,以便编译器可以告诉您何时不这样做.例如,如果你这样做了:

void f(double a) override {

编译器会给你这个诊断通知你它实际上没有覆盖任何东西,它甚至告诉你为什么它没有(“在第一个参数类型不匹配(‘int’与’double’)”):

main.cpp:15:18: error: non-Virtual member function marked 'override' hides Virtual member function

void f(double a) override { //double instead int here!

^

main.cpp:7:14: note: hidden overloaded Virtual function 'First::f' declared here: type mismatch at 1st parameter ('int' vs 'double')

Virtual void f(int a) {

^

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值