std::vector
是 C++ 标准库中的一个动态数组容器,可以存储任意类型的对象。重载函数是指在同一作用域内定义多个同名但参数列表不同的函数。当调用这些函数时,编译器会根据传递的参数类型和数量来决定调用哪个函数。
std::vector
提供了动态数组的功能,可以在运行时动态调整大小。std::vector
可以确保存储的对象类型一致,避免类型错误。std::vector
可以存储任意类型的对象,包括但不限于基本数据类型(如 int
, double
)、自定义类、结构体等。
std::vector
提供了方便的接口。假设我们有一个类 Person
,并且我们有一个重载的函数 printInfo
,分别用于打印 Person
对象的基本信息和详细信息。
#include <iostream>
#include <vector>
class Person {
public:
std::string name;
int age;
Person(std::string n, int a) : name(n), age(a) {}
};
void printInfo(const Person& p) {
std::cout << "Name: " << p.name << ", Age: " << p.age << std::endl;
}
void printInfo(const Person& p, bool detailed) {
if (detailed) {
std::cout << "Detailed Info: Name: " << p.name << ", Age: " << p.age << std::endl;
} else {
printInfo(p);
}
}
int main() {
std::vector<Person> people = { {"Alice", 30}, {"Bob", 25}, {"Charlie", 35} };
for (const auto& person : people) {
printInfo(person); // 调用基本信息的重载函数
printInfo(person, true); // 调用详细信息的重载函数
}
return 0;
}
原因:可能是由于传递的参数类型不匹配,或者编译器无法确定调用哪个重载函数。
解决方法:
例如,假设我们有以下重载函数:
void foo(int x);
void foo(double x);
如果我们调用 foo(10)
,编译器会自动选择 foo(int x)
。但如果我们调用 foo(10.0)
,编译器会自动选择 foo(double x)
。
如果出现歧义,可以使用显式类型转换:
foo(static_cast<int>(10.0)); // 显式调用 foo(int x)
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云