zoukankan      html  css  js  c++  java
  • 继承中指向的迷茫(仍旧犯迷糊)

    #include<iostream>
    using namespace std;
    class Father
    {
    public:
    Father()
    {
    cout << "i am father 
    ";
    }
    virtual void print()
    {
    cout << " 我是父类的:";
    cout << this->f << endl;
    }
    public:
    int f;
    };
    
    class Child :public Father
    {
    public:
    Child()
    {
    cout << "i am child 
    ";
    }
    virtual void print()
    {
    cout << " 我是子类的: ";
    cout << this->f << endl;
    cout << this->c << endl;
    }
    public:
    int c;
    };
    void objplay(Father *tem1)
    {
    cout << "形参为 Father *tem1 的 tem1->f==========>";
    cout << tem1->f << endl;
    }
    
    void objplay2(Child *tem2)
    {
    cout << "形参为 Child *tem2 的 tem2->c==========>";
    cout << tem2->c << endl;
    cout << "形参为 Child *tem2 的 tem2->f==========>";
    cout << tem2->f << endl;
    }
    int main()
    {
    Child c1;
    Father f1;
    c1.c = 5;
    c1.f = 6;
    cout << "c1.print()=====> ";
    c1.print();//调用子类的 输出为6
    f1.f = 7;
    cout << "f1.print()=====> ";
    f1.print();//调用父类的 输出为7
    //Child *c2; 这样子写就会出错,因为指针使用的时候必须必须分配内存空间
    Child *c2 = new Child;//一旦用类名字定义函数就会调用析构函数。
    //Father *f2;
    Father *f2 = new Father;
    c2->c = 8;
    c2->f = 9;
    cout << "c2.print()=====> ";
    c2->print();//调用子类的
    f2->f = 10;
    cout << "f2.print()=====> ";
    f2->print();//调用父类的
    objplay(&c1);// 这里虽然是父类的指针,但是指向的是子类的对象地址。所以调用显示的是子类的
    objplay(&f1);//父类
    objplay(c2);//这里居然也是调用的子类的值
    objplay(f2);//父类
    objplay2(&c1);
    //objplay2(&f1); 出错
    objplay2(c2);
    //objplay2(f2); 出错
    system("pause");
    }
    

      

    #include<stdio.h>
    #include<stdlib.h>
    class A
    {
    public:
    	void FuncA()
    	{
    		printf("FuncA called
    ");
    	}
    	virtual void FuncB()
    	{
    		printf("FuncB called
    ");
    	}
    };
    class B : public A
    {
    public:
    	void FuncA()
    	{
    		A::FuncA();
    		printf("FuncAB called
    ");
    	}
    	virtual void FuncB()
    	{
    		printf("FuncBB called
    ");
    	}
    };
    void main(void)
    {
    	B  b;
    	A  *pa;
    	pa = &b;
    	A *pa2 = new A;
    	pa->FuncA(); //这里的pa已经成为指向子类的指针了,所以调用的函数AB在用VIrtual的情形下,调用B的
    	pa->FuncB();// ( 4)
    	pa2->FuncA(); //( 5)
    	pa2->FuncB();
    	delete pa2;
    	system("pause");
    }
    

      

  • 相关阅读:
    python中的编码问题
    CVPR2018 Tutorial 之 Visual Recognition and Beyond
    hdu 1376 Octal Fractions
    hdu 1329 Hanoi Tower Troubles Again!
    hdu 1309 Loansome Car Buyer
    hdu 1333 Smith Numbers
    hdu 1288 Hat's Tea
    hdu 1284 钱币兑换问题
    hdu 1275 两车追及或相遇问题
    hdu 1270 小希的数表
  • 原文地址:https://www.cnblogs.com/xiaochige/p/6709710.html
Copyright © 2011-2022 走看看