ETH官方钱包

前往
大廳
主題

在C(程序式語言,Procedural Programming)中引入C++(物件導向,Object-Oriented)特性

Yang | 2023-02-19 09:59:29 | 巴幣 0 | 人氣 227

拿前2篇寫的範例改造

Before:
namespace Tools
{
    const int GetBuildDate(char *buffer)
    {
        return sprintf(buffer, "%s", __DATE__);
    }

    const int GetBuildTime(char *buffer)
    {
        return sprintf(buffer, "%s", __TIME__);
    }

    const int GetFilePath(char *buffer)
    {
        return sprintf(buffer, "%s", __FILE__);
    }

    const int GetLineNumber(char *buffer)
    {
        return sprintf(buffer, "%d", __LINE__);
    }
}

char buildInfo[128];
int buildInfoLen = -1;
buildInfoLen = Tools::GetBuildDate(buildInfo);

After:
namespace Tools
{
    class Functions
    {
        public:
            static const int GetBuildDate(char *buffer)
            {
                return sprintf(buffer, "%s", __DATE__);
            }

            static const int GetBuildTime(char *buffer)
            {
                return sprintf(buffer, "%s", __TIME__);
            }

            static const int GetFilePath(char *buffer)
            {
                return sprintf(buffer, "%s", __FILE__);
            }

            static const int GetLineNumber(char *buffer)
            {
                return sprintf(buffer, "%d", __LINE__);
            }
    };
}

char buildInfo[128];
int buildInfoLen = -1;
buildInfoLen = Tools::Functions::GetBuildDate(buildInfo);

隨著功能的擴充,C的做法就是一直擴充方法,但從物件導向的角度看,都是公開的(public)方法,
但只要稍微做一些改造,就能擁有封裝(Encapsulation)和繼承(Inheritance)等物件導向特性

class Functions
{
    private:
    protected:
    public:
};

class TimeFuncs : public Functions
{
    private:
    protected:
    public:
};

class LogFuncs : public Functions
{
    private:
    protected:
    public:
};

C的結構(struct)是用來包裝公開的(public)欄位和方法,也是可以改造成class

Before:
struct MySample
{
};

After:
class MySample
{
};
送禮物贊助創作者 !
0
留言

創作回應

更多創作