如何使用 C++ 中的原语初始化类(如 std::字符串从 const char* 初始化)

How to initialize a class with a primitive in C++(like std::string initialized from const char*)

本文关键字:初始化 字符串 const char C++ 何使用 原语 std      更新时间:2023-10-16

一段时间以来,我一直想知道的是,在许多不同的语言中,现在在 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;