- 浏览: 401210 次
- 性别:
- 来自: 上海
文章分类
- 全部博客 (309)
- xaml C# wpf (0)
- scala java inner clas (1)
- Tools UML Eclipse UML2 (1)
- Timer .NET Framework (1)
- perl (6)
- python function paramter (1)
- Python Docstring (1)
- Python how to compare types (1)
- Python (8)
- java (5)
- C# (76)
- C# WPF (0)
- p4 (0)
- WPF (46)
- .net (6)
- xaml (1)
- javascript (40)
- windows (10)
- scala (4)
- winform (1)
- c++ (48)
- tools (12)
- cmd (1)
- os (0)
- CI (0)
- shell (0)
- C (2)
- haskell (49)
- functional (1)
- tool (1)
- gnu (1)
- linux (1)
- kaskell (0)
- svn (0)
- wcf (3)
- android (1)
最新评论
There are 3 types of inheritances in classes inheritance in C++; they are
- public inheritance
- protected inheritance
- protected inheritance
as for the synonym of the type of inheritances, public inheritance is also know as type inheritance, while the private inheritance is also know as implementation inheritancfe.
A public derivation is refered to as type inhertitance, the dervied class is a subtype of the bse classes; it overrides the implementation of all type-specific member funcitons. of the base class while inheriting those that are shared. The derived class in general reflects is-a relationship
While we know a lots can be found abou the public inheritance, here we are not going into details further.
A private derivation is refered to as implementation inheritance, the derived class does not support the public interface of hte base directly. rather, it wishes to reuses the implementation of the base class while providing its own interface. To illustrate the issues involved, let's implements a PeekbackStack.
Let's see an examle.
suppose that we are subclass a IntArray class (a custom class) and provide additional functionality such as the ability to peek the back of the stack, which we call the subclass PeekbackStack.
for illustration purpose, this is the simplified version of IntArray code.
class IntArray { public: IntArray(int size) : _size(size) { init(size, 0); } IntArray(const IntArray & rhs) { init(rhs.size(), rhs.ia); } int size() const { return _size; } int& operator[](int index) { return ia[index]; } virtual ~IntArray() { delete[] ia; } private: void init(int sz, int * array_) { _size = sz; ia = new int[_size]; for (int i = 0; i < _size; ++i) { if (! array_) ia[i] = 0; else ia[i] = array_[i]; } } protected: int _size; int *ia; };
if you are using the public inheritance, you might implement the code as follow.
class PeekbackStack : public IntArray { private: const int static bos = -1; public: explicit PeekbackStack(int size) : IntArray(size), _top(bos) { } bool empty() const { return _top == bos; } bool full() const { return _top == size() - 1; } bool top() const { return _top; } int pop() { if (empty()) { /* handle error condiiton */ return ia[_top --]; } } void push(int value ) { if (full() ) { /* handle error condition */ ia[++_top] = value; } } bool peekback(int index, int & value) const; private: int _top; }; inline bool PeekbackStack::peekback(int index, int & value) const { if (empty() ) { /* handle error condition */ } if (index < 0 || index > _top) { value = ia[_top]; return false; } value = ia[index]; return true; }
This is all good, except that there is a by-prpduct, whereas , Program using the new PeekbackStack class may also make inappropriate use of its IntArray base class public interface, for example.
extern void swap(IntArray&, int, int); Peekbackstack is(1024); // oops: unexpected misuse of the PeekbackStack swap(is, i , j); is.sort(); is[0] = is[512];
So, the public inheritance represents a is-a relationship, while reflected back in our case, we can see that PeekbackStack is a special kind of IntArray, so you can expect that the operation that is applicable to PeekbackStack as well. so we can see that public inheritance is not the best fit for our case, what we want to is to restrict the user to the interfaces that is defined by us.
So how to address that, here comes the private inheritance. Let's see how we impl the private inheritance through the use of private inheritance
the solution is quite easy, you just change the public keyword with the private in the class derivation list.
class PeekbackStack: private IntArray { ... }
as a side note, a private base class reflects a form of inheritance that is not based on subtype relationship. The entire public interface of the base class becomes private in the derived class. Each of the preceding misuses of a PeekbackStack class instance is now illegal except witin in friend and member functions of the derived class.
Thus, it may as well deserve to talk about composition versus inheritance as far as we have private inheritance covered.
Since, after all with the private inheritance, we have achieved a kind of has-as relationship with regards to the IntArray classes.
Here is the new PeekbackStack implementaion with Composition pattern .
class PeekbackStack { private: const int static bos = -1; public: explicit PeekbackStack (int size): stack (size), _top(bos) {} bool empty() const { return _top == bos; } bool full() const { return _top == stack.size() - 1; } int top() const { return _top; } int pop() { if (empty() ) { // handling error } return stack[_top -- ]; } void push(int value) { if ( full() ) { // handle error condition } stack[++_top] = value; } bool peekback(int index, int & value) const; private: int _top; IntArray stack; };
so you may wonder when to use private inheritance and when to use the composition by references/value?
so this is a very good guidelines as whether to use composition or private inheritance in a class design in in which a has-a relationship exists
- If we wish to override any of the virtual functions of a class, we must inherit from it privately.
- If we wish to allow the class to refer to one of a hierarchy of possible types, we must use composition by reference
- If as with our PeekbackStack class, we wish simply to reuse the implementation, composition by value is to be preferred over inheritance. If a lazy allocation of the object is desired, composition by reference (useing a pointer) is the generally preferred design choice.
So we have covered the private and public inhertance, let's see why we have protected inheritance...
Before we introduce the protected inheritance, let's first examing the "exemping individual members"... since with private inhertiance, protected and public members are now all becomes private, in our example, you cannot allow the client to access the IntArray::size() method (which should be the same if the PeekbackStack class need to provide a size() method).
So what you can do is as follow.
class PeekbackStack : private IntArray { //.... public: // you can allow the client to access the IntArray size method by exempting the size method in the public section using IntArray::size; // you can allow further subsequent derivation access to the protected members. you can exempt individual members in the protected section protected: using IntArray::_size; using IntArray::ia; //.... };
However, this is tedious work and further, suppose that if we change the hierarchy so that
Stack inherits IntArray, => PeekbackStack inherits Stack, if we were using the private inheritancfe, we cannot allow the PeekbackStack to override some members, while protected inheritaince provides a perfect balance/compromise.
so if you do
class Stack : protected IntArray { ... }
then it you can easilty do
class PeekbackStack : public Stack { ... }
发表评论
-
不安装Visual Studio,只用Windows SDK搭建VC环境
2013-12-31 21:52 15345首先你需要下载的是 Microsoft Windows S ... -
rpath - runtime search path
2013-04-03 11:36 1021RPath is a very interesting to ... -
C++ - autogenerated copy constructor and assignment operator gotchas
2013-01-24 13:32 773It has been changed that the s ... -
c++ - rethrow a exception gotchas
2012-12-23 10:57 972As in my prevoius example in j ... -
c++ -typeid operator
2012-10-15 22:30 1065typeid is the one of the meager ... -
c++ - dynamic_cast revisit
2012-10-14 21:21 781There are several built-in type ... -
c++ - virtual inheritance example 1
2012-10-14 15:25 830we have discussed the virtual i ... -
c++ - virtual inheritance
2012-10-12 08:58 993As we have discussed in the pos ... -
c++ - vritually virtual new
2012-09-27 23:59 962Let's see what if we want to cl ... -
c++ - virtual destructor
2012-09-27 22:01 981As we all know that virtual des ... -
c++ - vritual function and default arguments
2012-09-27 08:56 1000As we all know that we virtual ... -
c++ - template specialization and partial specialization
2012-09-26 22:38 1336in this post, we are going to e ... -
c++ - member template in class template
2012-09-26 08:19 944class member template can be us ... -
c++ template class and the pattern to use its friends
2012-09-25 23:47 992template class may defined thei ... -
c++ - Friend declaration in class Template
2012-09-25 08:47 1214There are three kinds of friend ... -
c++ - class template default parameters
2012-09-25 08:18 861the template has parameter, it ... -
c++ - operator new and delete and an example of linked list stores by new/delete
2012-09-24 07:53 594The operator new and delete ope ... -
c++ - delete(void *, size_t) or delete(void *)
2012-09-24 07:18 1173In my previous dicuss, we have ... -
c++ - placement operator new() and the operator delete()
2012-09-23 15:22 877A class member operator new() c ... -
c++ - overloaded subscript operator - []
2012-09-23 08:50 1197You can overload the subscript ...
相关推荐
Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x ...
- **Mixed-Type Expressions**: Discussion of type conversions that occur when performing arithmetic operations involving different data types. - **Common Bugs with = and ==**: Explanation of common ...
The book features 240 C++ applications with over 15,000 lines of proven C++ code, and hundreds of tips that will help you build robust applications. Start with an introduction to C++ using an early ...
One of the most fundamental aspects of C++ highlighted in the book is the concept of viewing it not as a single monolithic language but as a federation of related sub-languages. This perspective is ...
Learn Visual C++ through the Teach Yourself series, with sections on: Q&A, Do's and Don'ts, Workshop, Shaded syntax boxes, Type/Output/Analysis icons. Week One starts you with Visual C++. After ...
指针的类型(The Type of a Pointer) 加上多态之后(Adding Polymorphism) 第2章 构造函数语意学(The Semantics of constructors) 2.1 Default Constructor的建构操作 “带有Default Constructor”的Member ...
Assuming no familiarity with C++, or any other C-based language, you’ll be taught everything you need to know in a logical progression of small lessons that you can work through as quickly or as ...
Basics of C++ 1.C++程序结构 Structure of a program 2.变量和数据类型 Variables and Data types 3.常量 Constants 4.操作符/运算符 Operators 5.控制台交互 Communication through console 3.控制结构和...
- **Type System Unification**: Section 8.2.4 discusses the unification of the type system in C++/CLI. - **Pointers, Handles, and Null**: Section 8.2.5 explores the use of pointers, handles, and null...
This updated handy quick C++ 14 guide is a condensed code and syntax reference based on the newly updated C++ 14 release of the popular programming language. It presents the essential C++ syntax in a ...
This updated handy quick C++ 14 guide is a condensed code and syntax reference based on the newly updated C++ 14 release of the popular programming language. It presents the essential C++ syntax in a ...
Google recommends using the latest stable version of C++. At the time of this guide's publication, that would be C++17 or later. Keeping up-to-date with the language helps take advantage of new ...
Based on the provided information from the file "Addison.Wesley.C++.by.Dissection.2002.pdf," we can derive a comprehensive overview of the C++ programming language as covered in this text. The book is...
differentiate between inheritance of interface and inheritance of implementation. 条款35:考虑virtual函数以外的其他选择 consider alternatives to virtual functions. 条款36:绝不重新定义继承而来的non-...
### Google C++编程规范中文版知识点详述 #### 一、背景 Google C++编程规范是一份详尽的文档,旨在指导开发人员编写高质量、可维护的C++代码。这份文档由Google内部多位资深工程师共同制定,是C++开发者的重要...
类型转换在某些情况下是必要的,但应避免使用C风格的转换(如`(type)`),而是使用更安全的C++风格的转换。 - **流 (Streams)** 流(如`std::cout`和`std::cin`)提供了一种方便的方式来输入输出数据。使用流时...
##### Run-Time Type Information (RTTI)(运行时类型信息) - RTTI的使用及其局限性。 ##### Casting(类型转换) - 不同类型的转换规则和推荐做法。 ##### Streams(流) - 输入输出流的使用技巧。 ##### ...
- **Use of const**:使用`const`关键字来表示不可修改的数据成员或函数参数。 - **Integer Types**:使用固定宽度整型(如`int32_t`)来确保跨平台的一致性。 - **64-bit Portability**:编写64位兼容的代码,确保...