継承と虚関数の入門について
2097 ワード
先日面接に行って、次の問題にぶつかって、出力は何ですか?
以下にsolutionのpartがあります.
#include <iostream>
using namespace std;
class Base
{
public:
virtual void function()
{
cout<<"function in Base
";
}
void function (int param)
{
cout<<"function in Base with param
";
}
};
class Derived : public Base
{
public:
virtual void function()
{
cout<<"function in Derived
";
}
void function(int param)
{
cout<<"function in Derived with param
";
}
};
void main()
{
Base base;
Derived derived;
base.function();
base.function(1);
derived.function();
derived.function(1);
Base * print = (Base *)&derived;
print->function();
print->function(1);
}
以下にsolutionのpartがあります.
#include <iostream>
using namespace std;
class Base
{
public:
virtual void function()
{
cout<<"function in Base
";
}
void function (int param)
{
cout<<"function in Base with param
";
}
};
class Derived : public Base
{
public:
virtual void function()
{
cout<<"function in Derived
";
}
void function(int param)
{
cout<<"function in Derived with param
";
}
};
void main()
{
Base base;
Derived derived;
base.function();//function in Base,
base.function(1);//function in Base with param,
derived.function();//function in Derived,
derived.function(1);//function in Derived with param,
Base * print = (Base *)&derived;// (Base *),
print->function();// , Base , , vbtl ,
print->function(1);// , Base , function() Base function,function in Base with param
}