有没有办法限制传递给方法的参数类型?
我试图将方法接受的参数限制为一个特定的用户定义类,但到目前为止还没有找到一种方法来做到这一点。
有办法吗?
这是我的代码:
class Item {
public:
std::string name;
Item(std::string n) { name = n; }
}
class Container {
private:
std::string name;
std::string description;
std::vector<Item> contents;
public:
Container(std::string n, std::string des) {name = n; description = des;}
void Container::addItem(Item item) {
if (typeid(item) == typeid(Item)) {contents.push_back(item);}
}
}
// code from test file:
WHEN("I try to add something which is not an Item.") {
std::string helment = "helmet";
std::vector<Item> contentsBefore = merchant.get_contents();
merchant.addItem(helmet); // here a string is added to class attribute "contents" via the above addItem method
std::vector<Item> contentsAfter = merchant.get_contents();
THEN("The container should not be updated to add the item.") {
REQUIRE(contentsBefore == contentsAfter);
}
}
回答
我有一个具有字符串属性的类,我正在尝试测试第二个类的方法,以便它只接受第一个类的对象,但是如果我只是尝试将字符串传递给它,它会接受输入的参数.
不,它没有。
它将字符串参数隐式转换为 an,Item因为单参数构造函数用作用户定义的转换。为了防止这种情况,请使用关键字explicit:
class Item {
public:
std::string name;
explicit Item(std::string n) { name = n; }
}
这意味着您仍然可以Item从std::string...创建一个,但只能是显式的(即,它禁用了您不想要的隐式转换)。
进一步阅读参考:
- 转换构造函数
- 转换计算表达式时可能出现的(标准转换是最有可能绊倒你,你已经找到了隐含的用户定义一个后)