我只是想知道。如果派生类使用公共继承从基类继承,并且它还重新定义了一个基类公共成员函数,如果派生类的实例调用print(),编译器会使用它吗? print是在基类中定义的,并在派生类中重新定义?非常感谢!!
答案 0 :(得分:3)
通过在派生类中重新定义基类成员函数,新定义隐藏旧定义。
因此,在派生类的范围内,只能看到新的定义。
class Base
{
public:
void print() { std::cout << "b \n"; }
};
class Derived : public Base
{
public:
void print() { std::cout << "d \n"; }
};
int main(void)
{
Base b;
Derived d;
Base *pb = &d;
Derived *pd = &d;
b.print(); // Calls Base::print()
d.print(); // Calls Derived::print()
pb->print(); // Calls Base::print()
pd->print(); // Calls Derived::print()
getchar();
return 0;
}
答案 1 :(得分:1)
编译器使用对象的静态类型来确定要调用的函数。包含在派生类中声明的成员函数的任何名称都隐藏了基类中具有相同名称的声明。
例如
#include <iostream>
#include <string>
class Base
{
public:
Base() : data( 10 ) {}
void f( char ) { std::cout << "Base::f( char )" << std::endl; }
void f( int ) { std::cout << "Base::f( int )" << std::endl; }
int data;
};
class Derived : public Base
{
public:
Derived() : data( "Hello World!" ) {}
void f( double ) { std::cout << "Derived::f( double )" << std::endl; }
std::string data;
};
int main()
{
Base b;
b.f( 0 );
b.f( 'A' );
std::cout << b.data << std::endl;
std::cout << std::endl;
Derived d;
d.f( 0 );
d.f( 'A' );
std::cout << d.data << std::endl;
std::cout << std::endl;
Base *pb = new Derived;
pb->f( 0 );
pb->f( 'A' );
std::cout << pb->data << std::endl;
delete pb;
return 0;
}
程序输出
Base::f( int )
Base::f( char )
10
Derived::f( double )
Derived::f( double )
Hello World!
Base::f( int )
Base::f( char )
10
使用虚函数代替非虚函数提供多态性。
例如
#include <iostream>
#include <string>
class Base
{
public:
Base() : data( 10 ) {}
virtual ~Base() {}
virtual void print() const { std::cout << data << std::endl; }
int data;
};
class Derived : public Base
{
public:
Derived() : data( "Hello World!" ) {}
void print() const
{
Base::print();
std::cout << data << std::endl;
}
std::string data;
};
int main()
{
Base b;
b.print();
std::cout << std::endl;
Derived d;
d.print();
std::cout << std::endl;
Base *pb = new Derived;
pb->print();
delete pb;
return 0;
}
程序输出
10
10
Hello World!
10
Hello World!