I am having trouble figuring out why this program works. I wrote it based on my notes (OOPP and classes) but I do not understand how exactly it works? I would appreciate any help!
Here is the code:
#include <iomanip>
#include <iostream>
using namespace std;
class Base{
public:
void f(int) {std::cout<<"i";}
};
class Derived:Base{
public:
void f(double){std::cout<<"d";}
};
int main(){
Derived d;
int i=0;
d.f(i);
}
I have tried making cout statements to show me how everything is passed and runs, but it will not allow me to cout anything.
CodePudding user response:
This program defines a class called Base, which has a member function called f that takes an int parameter. It also defines a class called Derived, which inherits from Base and has a member function called f that takes a double parameter.
In the main function, an object of type Derived is created, and an int variable is initialized to 0. The member function f is then called on the Derived object, passing in the int variable as a parameter.
When the member function f is called on the Derived object, the compiler looks for a matching function signature in the Derived class. Since there is a function with the same name and parameter list in the Derived class, that function is called. The function in the Derived class prints out a "d", indicating that it was called.
CodePudding user response:
Base::f(int)将被Derived::f(double)覆盖,d.f 输出为d