继承.为什么是这个输出
Inheritance. Why this output?
下面的程序打印3和4,但是我看不懂。有人能一步一步地解释我为什么有这个输出吗??
#include <iostream>
using namespace std;
class A{
public:
int f(int x){
cout << x << " " << endl;
}
};
class B : public A{
public:
int f(int y){
A :: f(y+1);
}
};
void g(A a, B b){
a.f(3), b.f(3);
}
int main(){
B p;
B q;
g(p,q);
system("pause");
return 0;
}
首先,您没有虚函数,因此将调用相应类中的函数。因此,可以简单地称其为a::f(3)
和B::f(3)
。其次,即使f 是虚拟的,您也可以通过值传递g
的参数,这意味着向上转换发生,因此在g
中,您只需拥有A
的实例和B
的实例,不涉及多态性。因此输出为:
3
4
相关文章:
- 为什么我的代码在输出中增加了93天
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 为什么rk4.do_step不输出C++中的初始条件
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 为什么我在输出端得到 nan?
- 为什么递归函数的最终输出是 5?
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 为什么输出精度没有正确舍入?
- 为什么这个程序的输出不如预期
- 有人可以向我解释为什么控制台输出 0 吗?
- 为什么文件不是由 F 流创建的,或者即使它是输出只是垃圾值?
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 为什么在这种情况下,bool 类型的输出等于 0?
- 执行此代码时,它不显示任何输出.为什么?
- 使用相同消息重新引发新异常会导致垃圾输出.为什么?
- 我的程序产生错误的输出.为什么
- 怪异的输出:为什么这段代码会给出任何有意义的输出,更不用说这个了
- %n格式说明符程序,在不同的编译器上提供不同的输出.为什么?
- 我的简单类函数中出现意外输出.为什么
- 如果语句不求值为false?程序给出奇怪的输出.为什么