基类中向量的干净实例化
Clean Instantiation of a Vector in the Base Class
我正在处理 C++11 中的代码,与类构造和向量值相关的部分代码已经失控。如何使它更简洁?
我的工作与版本有关,并创建了一个类型为std::vector<uint16_t>
的版本号向量来保存一个值数组来表示格式1.0.0.25
的版本。我希望所有类都有一个版本,所以我把它放在基类中。然后,子项继承Base
并实例化版本。
目前,我的代码有一个版本类、一个基类和一个子类。开发人员将通过在 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 中不起作用。
如何缩短此时间?
我最近处理了这样的事情,我没有传递向量,而是使用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++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 为什么我不能更改实例化对象内部的向量?
- 基类中向量的干净实例化
- 没有操作员=的类型向量的实例化
- 是否可以使用将不同参数传递给构造函数的类的不同实例初始化向量
- make_pair并push_back基指针,并实例化基指针的向量
- (C++)用于实例化新对象并将其分配给指向相同对象类型的指针的 2D 向量的语法
- 在显式实例化向量时<someType>,someType 默认构造函数的用途是什么?
- C :序列化类实例的向量
- 从字符* 高效实例化向量<char>
- 使用向量<向量>成员实例化对象时的隔离错误<int>
- 类对象的向量及其实例化
- C++ 避免向量<bool>实例化
- 实例化一个二维向量,其中一组对作为单元值
- 在 C++ 中将"this"添加到类实例化的向量
- C++向量元素是否动态实例化
- 如何实例化对象的静态向量
- C++错误:初始化结构实例的向量数组成员
- 如何在c++中显式实例化MPL向量的所有成员的模板