C/C++语法方面的一些小问题

1、指向子类对象的基类指针,可不可以调用子类中定义的成员,sizeof(*这个指针)的结果是哪个类的大小?


1、指向子类对象的基类指针,可不可以调用子类中定义的成员,sizeof(*这个指针)的结果是哪个类的大小?
答:
指向子类对象的基类指针,不可以调用子类中定义的成员。连编译都过不了,报错如下:
error:’class Base’ has no member named ‘print’
sizeof()的结果是基类的大小
为什么产生这样的疑问?
因为多态现象。我们可以通过指向子类的基类指针访问子类中对基类重写的虚函数,正因为有这个特殊现象的存在,才导致我产生上述问题。
结论:
使用什么类型的指针,就会用什么类型的方式去访问指针上的那片内存。由于子类继承基类,所以基类指针只能访问到子类对象中基类子对象的那部分内存。多态,是因为编译器改变了基类虚表指针所指的虚表中的虚函数的地址。
验证程序如下:

#include <iostream>
using namespace std;
class Base{
public:
    Base(){
        cout << "Base" << endl;
    }
private:
    int m_base;
};
class Der:public Base{
public:
    Der(const Base &base):Base(base){
        cout << "Der(const Base &base)" << endl;
    }
    void print(void){
        cout << "void Der::print(void);" << endl;
    }
private:
    int m_der;
};
int main(void){
    Base base;
    Der der(base);
    Base *p_Base = &der;
    //p_Base->print();//编译失败
    cout << "sizeof *p_Base " << sizeof(*p_Base) << endl;
    cout << "sizeof base " << sizeof(base) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/displaymessage/article/details/80889231