20150310的一些总结

1.今天被朋友问了一个问题:

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>

using namespace std;

class father{
    public:
        void run()
        {
            start();
        }
    protected:
        virtual void start(){

            cout << "father start" << endl;
        }
    private:
        int a;
        int dd;
        double fd;
};

class child : public father
{
    public:
        virtual void start(){
            cout << "child start" << endl;
        }
        void getfather(){
            father* ff = this;
            father fd = *ff;
            fd.run();
        }
    private:
        int b;
        double d;
};

int main(int argc, const char *argv[])
{
    child chi;
    chi.run();
    return 0;
}
这个示例的输出结果:实际是:child start

此时run中调用的start()方法是派生类的start而不是基类中的start!问题是此时的访问start的方法是静态联编还是动态绑定?

先看一个示例:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

class D
{
    public:
        void printA(){
            cout << "A" << endl;
            printB();
        }
        virtual void printB(){
            cout << "B" << endl;
        }

};

int main(int argc, const char *argv[])
{
    D *d = NULL;
    d->printA();//错误,输出:A segmentfault 11
    D d2;
    d2.printA();//正常输出
    return 0;
}
分析:printA()是非虚成员函数,d-> 和d2. 都可以实现对它的访问,但是当访问虚函数时(多态性)d->实际指向的对象是空的,所以肯定会出错!

总结:虚函数的多态性表现不是基类指针指向派生类,实际上可以让一个派生类指针指向另一个派生类(同一个基类),实现多态!


#include <iostream>
#include <string>
#include <vector>
using namespace std;

class A{
    public:
        void run(){
            cout << " type:" << typeid(*this).name() << endl;
            print();
        }
    virtual void print(){
           cout << " type:" << typeid(*this).name() << endl;
           cout << "A" << endl;
        }
};

class B : public A{
    public:
        void print(){//隐藏了父类的print函数
            cout << "B" << endl;
        }
};

class C : public A{
    public:
        virtual void print(){
            cout << "C" << endl;
        }
};

int main(int argc, const char *argv[])
{
//    C *c = (C*)(A*)new B();
//    c->print();
    B *b = new B();
    b->run();
    cout << "----" << endl;
    B b2 ;
    b2.run();
    //    B *b2 = NULL;
//    b2->run();
    return 0;
}

当print是虚函数时输出:

 type:1B
B
----
 type:1B
B

当print是非虚函数时的输出:

 type:1A
 type:1A
A
----
 type:1A
 type:1A
A
分析:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值