C++ 控制代碼類的原理以及設計,控制代碼原理
控制代碼類存在的意義是為了彌補將衍生類別對象賦給基類對象時發生的切片效應。例如下面的程式:
multimap<Base> basket;Base base;Derived derive;basket.insert(base);//ok,add copy of base;basket.insert(derive);//ok,but derive sliced down to its base part.
也就是說在把衍生類別的對象賦值給基類的時候,會發生切片效益,衍生類別的非基類部分會被切掉,那麼就失去了本身的意義。為瞭解決這個問題我們可以
使用基於基類的指標或者引用,但是設計到指標問題的話就涉及到資源不使用後的釋放問題。這就引出了控制代碼類,它類似智能指標,可以在我們複製資源
的時候不用去擔心記憶體泄露的問題。整個程式的設計如下所示:
//Base.h#pragma onceclass Base{public:Base(void);virtual ~Base(void);virtual Base* clone() const;virtual void fine() const;private:int mb;};
//Base.cpp#include "Base.h"#include <iostream>using namespace std;Base::Base(void):mb(12){}Base::~Base(void){}Base* Base::clone() const{return new Base(*this);}void Base::fine() const{cout<<"Base fine function"<<endl;}
//Derive.h#pragma once#include "base.h"class Derive :public Base{public:Derive(void);virtual ~Derive(void);virtual Derive* clone() const;virtual void fine() const;private:int md;};
//Derive.cpp#include "Derive.h"#include <iostream>using namespace std;Derive::Derive(void):Base(),md(13){}Derive::~Derive(void){}Derive* Derive::clone() const{return new Derive(*this);}void Derive::fine() const{cout<<"Derive fine function"<<endl;}
//Handles.h #pragma once#include "Base.h"#include <iostream>class Handles{public:Handles(void);Handles(const Base&);Handles(const Handles& h);~Handles(void);const Base* operator->()const;const Base& operator*()const;Handles& operator=(const Handles&);private:Base*p;std::size_t*use;void dec_use(){if(--*use == 0){delete p;delete use;std::cout<<"delete resource"<<std::endl;}}};
//Handle.cpp #include "Handles.h"Handles::Handles(void):p(NULL),use(new size_t(1)){}Handles::Handles(const Handles& h):p(h.p),use(h.use){++*use;}Handles::Handles(const Base& item):p(item.clone()),use(new std::size_t(1)){}const Base& Handles::operator*()const{if(p) return *p;elsethrow std::logic_error("unbounded Handles");}const Base* Handles::operator->()const{if(p) return p;elsethrow std::logic_error("unbounded Handles");}Handles& Handles::operator=(const Handles& h){++*h.use;dec_use();p = h.p;use = h.use;return *this;}Handles::~Handles(){dec_use();}
//main.cpp#include <iostream>#include "Handles.h"#include "Derive.h"#include <vector>using namespace std;void main(){vector<Handles> mb;Base b;Derive d;mb.push_back(Handles(b));mb.push_back(Handles(d));mb[0]->fine();mb[1]->fine();system("pause");}
c++中 控制代碼類是什
c++中沒有所謂控制代碼類的概念
在windows編程中倒是有一個控制代碼的概念,類型是HANDLE,這個其實不是一個類,HANDLE在windows其實只是一個類型定義,其內部的類型是數實值型別(例如int),這個只是為了唯一標示一個對象/核心對象而已
C語言程式設計的原理是什?
你要看看彙編、電腦群組成原理
然後再看c
就知道很多東西
浩強的C隨便看看就好了
真正的東西還遠呢