• 虚函数和纯虚函数


    虚函数
    加上一个virtual就行了。

    #include <iostream>
    using namespace std;
    
    class A {
        public:
            A(int x):a(x) {}
            virtual void display() {
                cout << a << endl;
            }
        protected:
          int a;
    };
    
    class B:public A {
        public:
            B(int x1,int x2):A(x1),str(x2){}
            void display() {
                cout<<a<<endl;
                cout << str << endl;
            }
        private:
          int str;
    };
    
    int main()
    {
        B b(1,2);
        A *a=&b;
        a->display();
        return 0;
    }
    

    纯虚函数
    virtual 函数类型 函数名 (参数列表)=0;
    这样声明,然后再派生类中重新定义就行了,派生类中的重名函数不需要写virtual,如果需要再次派生,也可以加上。

    #include <iostream>
    #define Pi 3.14
    using namespace std;
    
    class Shape {
    	public:
    		Shape(double a=0):area(a){}
    		virtual double Area()=0;
    		virtual void Show() {
    			cout<<area<<endl;
    		}
    	protected:
    		double area;
    };
    
    class Circle:public Shape {
    	public:
    		Circle(double xx,double yy,double rr):Shape(),x(xx),y(yy),r(rr) {}
    		double Area() {
    			area=Pi*r*r;
    			return area;
    		}
    		virtual void Show() {
    			cout<<area<<endl
    			<<r<<endl
    			<<'('<<x<<','<<y<<')'<<endl;
    		}
    		friend ostream& operator <<(ostream &output,Circle &c);
    	private:
    		double x,y,r;
    };
    
    ostream& operator <<(ostream &output,Circle &c) {
    	output<<c.area<<endl
    		<<c.r<<endl
    		<<'('<<c.x<<','<<c.y<<')'<<endl;
    	return output;
    }
    
    int main()
    {
    	Circle c(1,1,1);
    	c.Area();
    	Shape *s=&c;
    	s->Show();	
    	cout<<c;
    	return 0;
    }
    
  • 相关阅读:
    树上问题
    Windows Server 2012 安装dll到GAC
    一妹子开车发现车不动,男友听完她电话崩溃了
    各浏览器对 window.open() 的窗口特征 sFeatures 参数支持程度存在差异
    FullCalendar日历插件说明文档
    Request url 各种属性值
    Your Job Is Not to Write Code
    Nice way for strip_tags a like
    sqlserver 三种恢复模式
    ASP.NET路由
  • 原文地址:https://www.cnblogs.com/xyqxyq/p/10350147.html
Copyright © 2020-2023  润新知