Home > Back-end > (turn) c about inheritance get dizzy
(turn) c about inheritance get dizzy
Time:10-23
Recently in the title of type c + +, always make mistakes about inheritance, before using the feeling is very good, some of the same code can pass some but not by very headache Want to ask where there's a better interpretation of the Such as this code calculates the distance to the origin: () is not in conformity with the result, only the output of the first input value
# include #include using namespace std; The class point1d { Protected: Float x; Public: Point1d (float a) { X=a; } Float short () { If (x<0) The return - x; The else return x; } }; The class point2d: public point1d { Protected: Float y; Public: Point2d (float a, float b) : point1d (a) { X=a; Y=b; } Float short () { Float d=SQRT (x * * y x + y); Return d; } }; The class point3d: public point2d { Protected: Float z; Public: Point3d (float a, float b, float c) : point2d (a, b) { X=a; Y=b; Z=c; } Float short () { Float d=SQRT (x * * y x + y + z * z); return d; } }; Int main () { The int type. Cin> The type; Point1d * p; float a,b,c; While (type!=0) { The switch (type) { Case 1: Cin> a; P=new point1d (a); break; Case 2: Cin> a> b; P=new point2d (a, b); break; Case 3: Cin> a> b> c; P=new point3d (a, b, c); break; } CoutCin> The type; } }
There is more to the previous version:
#include #include using namespace std; The class point1d { Protected: Float x; Public: Point1d float (p=0.0);//the line commented out via Float short () { Cin> x; If (x<0) The return - x; The else return x; } }; Class point2d: public point1d//complains here { Protected: Float y; Public: Float short () { Cin> X> y; Float d=SQRT (x * * y x + y); return d; } }; The class point3d: public point2d { Protected: Float z; Public: Float short () { Cin> X> y> Z; Float d=SQRT (x * * y x + y + z * z); return d; } }; Int main () { The int type. Cin> The type; While (type!=0) { Point1d * p; Switch (type)//if this operation, the result is not in conformity with the { Case 1: P=new point1d//if no this line will run this situation error Coutbreak; Case 2: P=new point2d; Coutbreak; Case 3: P=new point3d; Coutbreak; } } }