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");
    }
    

      

  • 相关阅读:
    09 python初学 (字符串)
    08 python 初学(字典)
    07 Python初学(元组)
    ubuntu 学习
    10 python 初学(Python 的编码解码)
    12 python 初学(深浅拷贝、集合)
    11 python初学 (文件)
    ubuntu 在 Windows 下的安装
    mysql常用命令总结
    关于Windows 7 下临时IPV6地址的问题,如何禁用它
  • 原文地址:https://www.cnblogs.com/xiaochige/p/6709710.html
Copyright © 2011-2022 走看看