简体   繁体   中英

C++ Inheritance Hierarchy for Numbers

I'm trying to implement a Number hierarchy in C++. I'm planning to write an abstract class Number and derive ComplexNumber from Number and derive Real and Imaginary classes from Complex and Integers, Naturals,.. but the problem is when I write NaturalNumber, there are bunch of setters, getters, variables which I don't use in NaturalNumber class.

Can I avoid this?

I think you have a bit of a design problem there :) .

An often useful guidance is to think of inheritance as an is a relationship.

If B inherits from A, that means B is an A .

With that we mean that B has all the abilities of A.

Obviously this still leaves some room for interpretation and it is the job of a good software architect to fill that :) . But it seems quite clear to me that Natural Number cannot inherit from Complex Number , because it does not have all the properties of a complex number. It doesn't have an irrational part, etc. If you really wanted to build hierarchy, it would be

Complex Number is a >  Real Number is a > Natural Number is a > Number. 

And the real and imaginary part of the complex number are are also > Real Numbers.

However, in a practical situation (as opposed to an exercise) you will probably be better off by using a flatter hierarchy. All of these things are numbers, but it doesn't quite make sense to inherit complex, real and natural number from another. You will likely be better off by just inheriting all of them from Number .

There are other ways to re-use code if needed, such as composition , as you already mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM