C++中的explicit

时间:2025-03-27 07:12:00
class VectorInt2D { public: VectorInt2D() { Init(); } explicit VectorInt2D(int x) // explicit防止隐式转换 { Init(x); } VectorInt2D(int x, int y) { Init(x, y); } VectorInt2D(const VectorInt2D& obj) { this->x = obj.x; this->y = obj.y; // 重新申请新的内存空间 uint32_t nLen = strlen(obj.m_pszClassName) + 1; m_pszClassName = new char[nLen]; strcpy_s(m_pszClassName, nLen, obj.m_pszClassName); } void Init(int x = 0, int y = 0) { uint32_t nLen = strlen("VectorInt2D") + 1; m_pszClassName = new char[nLen]; strcpy_s(m_pszClassName, nLen, "VectorInt2D"); this->x = x; this->y = y; } ~VectorInt2D() { if (m_pszClassName != nullptr) { delete m_pszClassName; m_pszClassName = nullptr; } } char* GetClassName() { return m_pszClassName; } int GetX() { return this->x; } int GetY() { return this->y; } private: char* m_pszClassName; int x; int y; }; void ShowPoint(VectorInt2D pos) { printf("%s x=%d y=%d\n", pos.GetClassName(), pos.GetX(), pos.GetY()); } int main(int argc, char* argv[]) { VectorInt2D pos1(1, 2); // 参数为对象自动匹配构造函数 这里匹配拷贝构造 ShowPoint(pos1); // 显式调用构造函数 VectorInt2D pos2(2); //编译错误,不能隐式调用其构造函数 ShowPoint(1); // error C2664: “void ShowPoint(VectorInt2D)”: 无法将参数 1 从“int”转换为“VectorInt2D” return 0; }