如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)
How to initialize a class with a primitive in C++(like std::string initialized from const char*)
一段时间以来,我一直想知道的是,在许多不同的语言中,现在在 c++ 中,你如何使用原语初始化对象?我很好奇 std::string 如何使用 const char* 初始化,我想知道是否有一种简单的方法可以做到这一点。抱歉,如果这个问题格式不正确,我只是在stackoverflow上没有找到这样的问题,这是我的第一个或第二个问题。谢谢!
如果你能写这样的东西:
std::string s = "hello world!";
这是因为string
类的构造函数采用const char *
std::string
是一个std::basic_string<char>
例如,如果要使用基元数据类型实例化自定义类的对象,则只需定义一个允许它的构造函数:
class MyCustomClass
{
public:
MyCustomClass(int a) : m_integer(a) {}
MyCustomClass(const char* s) : m_integer(std::atoi(s)) {}
int getValue() const { return m_integer; }
private:
int m_integer;
};
此类允许您像这样使用它:
MyCustomClass mcc1 = 2; // Use MyCustomClass(int a)
MyCustomClass mcc2 = "12"; // Use MyCustomClass(const char* s)
// Will print : 2
std::cout << mcc1.getValue() << std::endl;
// Will print : 12
std::cout << mcc2.getValue() << std::endl;
相关文章:
- 有没有办法在初始化字符串时避免来自 clang-tidy(fuchsia-default-arguments)的警告?
- 如何在 c++ 中初始化字符串的 2D 数组
- 在 C++ 中初始化字符串重要吗?
- 为什么我不能使用统一初始化初始化来初始化字符串?
- 使用大长度缓冲区初始化字符串流是否会使内存使用量加倍
- 在现代C++中初始化字符串的方式是否有不同
- 初始化字符串 c++ 数组中的值
- 初始化 c 字符串的向量
- 在 do-while 循环中初始化字符串将在检查条件之前跳转到它
- 初始化C++字符串向量的向量
- 初始化字符串矢量阵列时的错误
- 如何初始化字符串以包含C 中所需数量的数字数量
- C 在代码中初始化字符串变量时无控制台输出
- 初始化字符串时,额外的卷曲牙套
- 为什么我不能用"\x"初始化字符串
- 如何在C++中最好地初始化字符串向量
- 从二维数组中的char*初始化c++字符串时,读取大小为1的无效值
- C++初始化字符串数组
- 如何在C++中初始化字符串集
- 如何初始化字符串指针