C++: What is a class interface?
I know that in C++ there is no interface
keyword or whatsoever, but that it is more of a d开发者_运维知识库esign-pattern instead.
So, if I have an Apple
class, which contains information and methods to work on apples (color, sourness, size, eat, throw)..
- What would an interface to Apple look like?
- What do you usually need interfaces for?
You just use pure virtual functions in a class.
class IApple
{
public:
virtual ~IApple() {} // Define a virtual de-structor
virtual color getColor() = 0;
virtual sourness getSourness() = 0;
virtual size getSize() = 0;
virtual void eat() = 0;
};
Martin's illustrated an interface. Re your other question - what do you usually need them for:
- they can be used as base classes by functions that provide this API
- an interface may be a small part of the derived class's overall functionality; a derived class can implement many interfaces
- pointers or references to interfaces (possibly in containers) can be used in code to decouple that code from any particular implementation (i.e. as a base for run-time polymorphic code using virtual functions / dispatch)
- this can help reduce compile times and break cyclic dependencies
- the implementation might be provided by a caller or a factory method
- being able to vary the implementation often makes the system overall more flexible and reusable
- implementations that facilitate testing can be slotted in
- the interface itself may have value as a form of usage documentation (sometimes I even create interfaces as illustrates of expected template policy parameters, although there's no actual need to derive your policy from them)
- some design patterns work by changing the implementation during the lifetime of the containing object/code
- they can be used as a kind of annotation or trait for a class - even without providing any actual behaviour of their own - with other code checking whether the interface is a base when deciding on appropriate behaviour
A interface is a set of members eg. functions and variables that is shared between different classes so you can access the members of the interface without having to know which class it was in the first place, as long as it implements the interface you can be sure it has the members.
You can use it for example to iterate through different objects calling the same function on each.
精彩评论