c++ - 基类中 vector 的干净实例化

标签 c++ class c++11 vector

我正在使用 C++11 编写代码,与类构造和 vector 值相关的部分代码已经失控。我怎样才能使它更简洁?

我的工作与版本相关,并创建了一个类型为 std::vector<uint16_t> 的版本号 vector 。保存一个值数组来表示格式的版本 1.0.0.25 .我希望所有类都有一个版本,所以我把它放在基类中。然后 child 继承Base并实例化版本。

目前,我的代码有一个 Version 类、一个 Base 类和一个 Child 类。开发人员将通过在 Child 类的定义变量中设置值来对版本进行硬编码。我希望它易于查看和阅读。我的问题是 Child 类传递值的部分目前非常丑陋,我希望让它更简洁和可读。

代码是:

#include <vector>

namespace CodeStuff
{
namespace VersionStuff
{


typedef uint16_t VersionType;

class Version
{

public:
    Version(const std::vector<VersionType> & aNumbers, const VersionType aType = -1)
    {
        numbers_ = aNumbers;
        type_ = aType;
    }
private:
    std::vector<VersionType> numbers_;
    VersionType type_;
};

} // end namespace VersionStuff
} // end namespace CodeStuff

class Base
{
public:
    Base(const CodeStuff::VersionStuff::Version & aVersion) : version_(aVersion)
    {
    }

    const CodeStuff::VersionStuff::Version getVersion() const {return version_;}

private:
    const CodeStuff::VersionStuff::Version version_;
};


#define CHILD_VERSION {1, 0, 0, 25}

class Child : public Base
{
public:
    Child() : Base(CodeStuff::VersionStuff::Version{std::vector<CodeStuff::VersionStuff::VersionType>{CHILD_VERSION}}) {}
};



int main(int argc, const char * argv[]) {

    Child myChild();
}

我的问题是虽然我喜欢有一种简单的方法来查看 #define CHILD_VERSION {1, 0, 0, 25} 中的版本,构造函数调用非常难看:

 Child() : Base(CodeStuff::VersionStuff::Version{std::vector<CodeStuff::VersionStuff::VersionType>{CHILD_VERSION}}) {}

我想这样做:

Child() : Base(CHILD_VERSION) {}

但在 XCode 中,这会导致错误“没有匹配的构造函数来初始化类型 Base”。因为这是有效的语法:

std::vector<uint16_t> v({1, 0 ,0 ,25}); 

我不确定为什么短 Base(CHILD_VERSION)在 C++11 中不起作用。

我怎样才能缩短它?

最佳答案

我最近处理了一些非常类似的事情,我没有传递 vector ,而是使用 std::initializater_list 作为我获取简单常量版本号的途径。这是一个例子:

class Version {
  std::vector<unsigned> version;
 public:
  Version(const std::string & s);
  Version(std::initializer_list<unsigned> list) : version(list) {}
  bool operator== (const Version & other) const {
    return version == other.version;
  }
  bool operator< (const Version & other) const {
    return version < other.version;
  }
};

这里可以像这样创建一个版本:

Version v{1, 0 ,0 ,25};

您可以让您的基类也有一个 std::initializer_list 构造函数,并将其传递给您的 version_ 对象。

关于c++ - 基类中 vector 的干净实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45108988/

相关文章:

c++ - 跟随哪个会更有效率?

c++ - Opencv:cvGetMat 中的空指针(传递空数组指针)

c++ - 记录跨越多个文件的 namespace doxygen

python - 在运行时重新定义 Python 类

c# - 调用方法并直接读取/设置参数的私有(private)字段是否会破坏封装?

c++ - std::initializer_list<> 和一个引用参数

c++ - 使用 <ctime> 和指令重新排序进行基准测试

c++ - Qt: 为什么断网后 `QAbstractSocket::error(QAbstractSocket::SocketError)`信号没有产生?

c++ - 使用 python 扩展在 gdb 中打印 Eigen 类型时遇到问题

class - react-native Component 与 React.createClass 实现 UI 组件的优缺点?