父类子类都定义了同名成员变量,以及类member func语义

573 阅读1分钟
#include <iostream>
using namespace std;
class father
{
public:
    father(){ a = 3; };
    void print()
    {
        cout << "first:" << a << father::a << endl;
    }

    int a;

    void func()
    {
        cout << "hello world" << endl;
    }

    static void func2()
    {
        cout << "hello world 2" <<endl;
    }
};

class son : public father
{
public:
    son(){ a = 4; }
    void print()
    {
        cout << "second:" << a << "\t" << father::a << "\t" << son::a << endl;
    }
    int a;
};

int main()
{
    son s1;
    s1.print();

    cout << sizeof(father) << "\t" << sizeof(son) << endl;

    // 通过空对象访问类的非static成员函数的取巧方法
    father* f = (father*)0;
    f->func();

    // 通过类名直接访问static成员函数
    father::func2();
    //func2(); // compile error: ‘func2’ was not declared in this scope,说明类的static成员函数需要类作用域才可以调用

    return 0;
}

输出结果:

second:4        3       4
4       8
hello world
hello world 2

说明:

父类和子类可以定义同名变量,编译器会进行名字转换,所谓的name mangling,这样s1对象内存中会存在类似于father_a和son_a两个成员变量。
从sizeof(son)的输出结果为8也可以得出这个结论。