C++ Class Design

C++ Class Design

本文关键字:Design Class C++      更新时间:2023-10-16

目前我正在用以下结构开发我的大多数c++类,我想知道社区是否可以给我一些关于如何改进我的类设计的技巧,使其在未来更可移植,更友好,更易于维护。

#include <vector>
#include <iostream>
namespace CompanyName
{
    class Uri;
    class Regex;
    class String
    {
    public:
        String();
        String(const char*);
        String(const String&);
        virtual ~String();
        void trim();
        void erase();
        void remove(const int);
        void remove(const int, const size_t);
        void uppercase();
        void lowercase();
        bool is_null() const;
        bool is_empty() const;
        size_t length() const;
        void append(const String&);            
        bool compare(const String&) const;
        bool compare(const String&, const bool) const;
        void replace(const Regex&, const String&);
        std::vector<String> split(const Regex&) const;
        static const char* to_utf8(const String&);
        static const uint16_t* to_utf16(const String&);
        static const uint32_t* to_utf32(const String&);
        static String from_utf8(const char*);
        static String from_utf16(const uint16_t*);
        static String from_utf32(const uint32_t*);
        static String resource(const Uri&, const int);
        static String resource(const Uri&, const String&);
        String& operator=(String rhs);
        String& operator+(const String& rhs);
        String& operator+=(const String& rhs);
        bool operator==(const String&) const;
        bool operator!=(const String&) const;
        bool operator<(const String&) const;
        bool operator>(const String&) const;
        friend std::ostream& operator<<(std::ostream&, const String&);
        friend std::istream& operator>>(std::istream&, const String&);
        static const String null;
        static const String empty;
    protected:
        struct protected_pimpl;
        protected_pimpl* _protected_pimpl;
    private:
        struct private_pimpl;
        private_pimpl* _private_pimpl;
    };
    //we have to extract the content so as to not expose the UnicodeString.
    inline std::ostream& operator<<(std::ostream& stream, const CompanyName::String& rhs)
    {
        const char* value = String::to_utf8(rhs);
        stream << value;
        delete value;
        return stream;
    }
    inline std::istream& operator>>(std::istream& stream, const CompanyName::String& rhs)
    {
        const char* value = String::to_utf8(rhs);
        stream >> value;
        delete value;
        return stream;
    }
}

我想说的是,第一步,也是最好的一步是删除所有你不需要的东西。

考虑Monoliths unstring 的建议:当类被精简到它们的主要概念时,它们更易于维护和"面向未来"。

例如:为什么replace()需要是一个成员函数?或者to/from_utfX()函数?

你没有virtual成员函数,所以你的类显然不打算被多态使用。因此,使析构函数virtual是不必要的(并导致类具有不必要的v表),并且不需要protected pimpl。

而且,只要可能,总是选择自由函数(必要时声明为friend s)作为操作符,而不是成员函数。