构造函数
委托构造函数
委托构造函数(Delegating Constructor)是 C++11 引入的一个特性,允许一个构造函数调用同一个类的其他构造函数,以减少重复代码并提高可维护性。
Sales_data2(std::string s, unsigned cnt, double price)
: bookNo(s), units_sold(cnt), revenue(cnt * price) {}
Sales_data2() : Sales_data2("", 0, 0) {}
Sales_data2(std::string s) : Sales_data2(s, 0, 0) {}
Sales_data2(std::string s, unsigned cnt, double price)
是非委托构造函数,它是实际完成初始化的构造函数。Sales_data2()
和Sales_data2(std::string s)
是委托构造函数,它们通过Sales_data2("", 0, 0)
和Sales_data2(s, 0, 0)
调用非委托构造函数来完成初始化。
特点
- 所有构造函数最终都会调用那个带三个参数的构造函数。
- 委托构造函数不能有成员初始化列表;它只能通过调用另一个构造函数来初始化对象。
- 构造函数链最后必须有一个非委托构造函数来完成实际的初始化工作。
示例流程
-
Sales_data2 obj1;
调用默认构造函数Sales_data2()
→ 委托给Sales_data2("", 0, 0)
初始化。 -
Sales_data2 obj2("12345");
调用Sales_data2(std::string s)
→ 委托给Sales_data2(s, 0, 0)
→ 最终调用三参数构造函数。
这种方式让构造逻辑更清晰、简洁,并避免重复代码。
构造函数隐式转换
在 C++ 中,当你传递参数给构造函数时,语言只允许进行一次用户自定义的隐式类型转换(也称为一步转换)。这个规则是为了防止在对象构造过程中出现歧义或意外的行为。
#include <iostream>
#include <string>
class MyClass {
public:
// 构造函数接受 const char*
MyClass(const char* str) : str_(std::string(str)) {
std::cout << "Constructed from const char*" << std::endl;
}
// 构造函数接受 std::string
MyClass(const std::string& str) : str_(str) {
std::cout << "Constructed from std::string" << std::endl;
}
private:
std::string str_;
};
int main() {
MyClass obj1("Hello"); // 调用接受 const char* 的构造函数
MyClass obj2(std::string("World")); // 调用接受 std::string 的构造函数
return 0;
}
// 假设有一个额外的中间类型
class MyString {
public:
MyString(const char* s) : str(s) {}
operator std::string() const { return str; }
private:
std::string str;
};
MyClass obj4(MyString("Example")); // 错误:无法从 MyString 隐式转换为 std::string 或 const char*
explict
如果你有一个构造函数接受一个参数(例如:Sales_data2(std::string s)
),C++ 允许它在某些情况下被当作隐式转换函数使用。
void print_sales(const std::string& data);
const char *book = "C++ Primer";
print_sales(book); // 隐式类型转换
为了避免这种隐式转换,你可以将构造函数标记为 explicit
。
应该什么时候使用 explicit?
- 当你不希望某个构造函数被用于隐式类型转换时。
- 特别是在构造函数只有一个参数,或者其余参数都有默认值时,建议加上
explicit
。 - 建议:对于所有单参数构造函数,尽量使用
explicit
,除非你明确需要支持隐式转换,我建议所有只有一个参数的构造函数都禁止隐式转换,因为隐式转换容易造成理解困难。