gpt4 book ai didi

c++ - 是否可以从std::string继承以提供类型一致性?

转载 作者:行者123 更新时间:2023-12-04 16:42:03 24 4
gpt4 key购买 nike

我希望一个类(class)存储一个团队的名称。我可以为此使用std::string,但是从语义上讲它并不是真正正确的。 std::string表示我的团队名称不能为空或超过10个字符时的任何字符串。

class TeamName {
public:
TeamName(std::string _teamName) : teamName(std::move(_teamName))
{
if (teamName.length() == 0 || teamName.length() > 10) {
throw std::invalid_argumet("TeamName " + teamName + " can't be empty or have more than 10 chars." );
}
}

private:
std::string teamName;
};

我喜欢这样:我只检查一次名称的完整性,将来从未听说过此要求的开发人员将无法从其新函数中传播无效的名称,程序逻辑中显然存在放置异常的位置处理程序等

但是这种构造意味着我必须使用getter和setter来与名称进行交互,这会严重污染代码。但是,如果我继承自std::string,则代码几乎不变,我可以将TeamName完全视为std::string

class TeamName : public std::string {
public:
TeamName(std::string _teamName) : std::string(_teamName)
{
if (length() == 0 || length() > 10) {
throw std::invalid_argumet("TeamName " + teamName + " can't be empty or have more than 10 chars." );
}
}
};

这是不好的做法吗?从概念上来说,这对我来说是正确的。

用什么方法可以实现我想要的一致性,并且仍然能够使用包装器与使用字符串的方式没有什么不同?

最佳答案

在C++ 17中,您可以使用std::string_view作为隐式转换的目标类型:

class TeamName {
std::string val;
public:
TeamName(std::string name): val(std::move(name)) { /* snip */ }

operator std::string_view() const {
return val;
}
};

这使您可以在可以使用 TeamName的任何地方使用 std::string_view,同时不允许修改(因此,长度的不变性在对象创建后保持不变)。当然,这需要您应该使用对象的代码部分来了解 std::string_view

如果 std::string_view对您不可行,则可以定义到 const std::string&的转换。

关于c++ - 是否可以从std::string继承以提供类型一致性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59874237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com