Jason_C_ 2021-03-26 21:43 采纳率: 0%
浏览 13

问一下为什么 基类Shape的构造函数在每次声明派生类时都执行了,但是x,y却没有被赋值

  1. #include<iostream>
    #define pai 3.14
    using namespace std;
    class Shape
    {	protected:
    	float x,y;
    	public:
    	Shape(float a,float b){x=a;y=b;cout<<x<<endl;} //就是这句话
    	virtual void area()=0;
    
    };
    class T:public Shape
    {
    	public:
    	T(float a,float b):Shape(x,y){}
    	void area()
    	{ float s;
    	s=0.5*x*y; 
    	cout<<"triangleArea="<<s<<endl;}
     }; 
    class R:public Shape
    {public:
    	R(float a,float b):Shape(x,y){x=a;y=b;} //只有在派生类的构造函数中赋值时是有效的
    	void area()
    	{
    		cout<<"rectangleArea="<<x*y<<endl;
    	}
     }; 
    class C:public Shape
    {public:
    	C(float a,float b):Shape(x,y){x=a;y=b;}
    	void area()
    	{ 
    		cout<<"circleArea="<<pai*x*x<<endl;
    	}
     };
     int main()
     {	float x1,y;
     	cin>>x1>>y;
     	T t1(x1,y);
     	t1.area();
     	R r1(x1,y);
     	r1.area();
     	C c1(x1,y);
     	c1.area();
     	return 0;
     }

 

 
  • 写回答

2条回答 默认 最新

  • lemon-l 2021-03-26 21:55
    关注

    改成Shape(a,b)

    评论

报告相同问题?