C++介面與實現分離的2種方法 (C/C++)

來源:互聯網
上載者:User

方法一:使用另一個實作類別分裝類的私人成員和函數,這種方法稱為Pimpl方法。,也就是組合的方法。

#include <boost/shared_ptr.hpp>
#include <iostream>

class CTest
{
public:
 CTest();
 ~CTest() {std::cout<<"CTest destructor!"<<std::endl;}
 void do_something();

private:
 class CTestImp;
 boost::shared_ptr<CTestImp> pimpl_;
};

class CTest::CTestImp
{
public:
 CTestImp(){std::cout<<"CTestImp constructor!"<<std::endl;}
 ~CTestImp(){std::cout<<"CTestImp destructor!"<<std::endl;}
 void do_something();

private:
 CTestImp(CTestImp const &){}
 CTestImp & operator=(CTestImp const &){}
};

CTest::CTest(void)
{
 boost::shared_ptr<CTestImp> pImp(new CTestImp);
 pimpl_ = pImp;
}

void CTest::CTestImp::do_something()
{
 std::cout<<"Imp class do something."<<std::endl;
}

void CTest::do_something()
{
 pimpl_->do_something();
}

int main()
{
 CTest test;
 test.do_something();

 return 0;
}

 

方法二:使用抽象類別來實現介面與實現的分離。

x.h

#pragma once
#include <stdio.h>
#include "shared_ptr.hpp"
using namespace boost;

class X
{
public:
    virtual void f() = 0;
    virtual void g() = 0;

protected:
    ~X() { printf("~X/n");}
};

shared_ptr<X> createX();

x.cpp

#include "X.h"
#include <stdio.h>

class X_impl: public X
{
private:
    X_impl(){};   
    X_impl(X_impl const &);
    X_impl & operator=(X_impl const &);

public:
    ~X_impl(){printf("~X_impl/n");};
    virtual void f()
    {
      printf("X_impl.f()/n");
    }
    virtual void g()
    {
      printf("X_impl.g()/n");
    }
private:
    friend shared_ptr<X> createX();
};

shared_ptr<X> createX()
{
    shared_ptr<X> px(new X_impl);
    return px;
}

總結:
       介面與實現的分離,有助於我們對代碼實現的保護,特別是如果我們開發lib共別人使用使,更要注意。在實現分離的過程中,最好採用上面的第一種方法的智能指標boost::shared_ptr的實現,簡單安全。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.