问一下为什么 基类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;
     }

 

 

改成Shape(a,b)

您好,我是问答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632