在类属类中重载operator < 时无法从初始化列表转换为std::less<int>是因为什么
时间: 2023-06-19 08:02:50 浏览: 98
在类属类中重载 operator< 时,如果我们想要使用 std::less 比较器来比较两个对象,需要在类的定义中声明 std::less<int> 作为其第二个模板参数。例如:
```c++
template<typename T, typename Compare = std::less<T>>
class MyClass {
public:
bool operator<(const MyClass& other) const {
Compare cmp;
return cmp(value, other.value);
}
private:
T value;
};
```
在上述代码中,我们将 std::less<int> 作为 MyClass 的第二个模板参数,这样在 operator< 函数中就可以使用 Compare 类型的比较器来比较两个 MyClass 对象了。
关于初始化列表转换的问题,我猜测你可能是这样使用的:
```c++
template<typename T, typename Compare = std::less<T>>
class MyClass {
public:
MyClass(T value) : value(value), cmp() {}
bool operator<(const MyClass& other) const {
return cmp(value, other.value);
}
private:
T value;
Compare cmp;
};
```
在上述代码中,我们在 MyClass 的构造函数中使用了初始化列表来初始化成员变量 value 和 cmp。但是,由于 cmp 是一个对象,需要进行构造和初始化,而初始化列表中并没有指定其初始化值,因此编译器会尝试使用默认构造函数来创建一个 Compare 类型的对象。但是,由于 Compare 不一定有默认构造函数,因此编译器会报错。
为了解决这个问题,我们可以将 cmp 的初始化放到构造函数体中,如下所示:
```c++
template<typename T, typename Compare = std::less<T>>
class MyClass {
public:
MyClass(T value) : value(value) {}
bool operator<(const MyClass& other) const {
Compare cmp;
return cmp(value, other.value);
}
private:
T value;
};
```
在上述代码中,我们将 cmp 的初始化放到了 operator< 函数中,这样就可以避免初始化列表转换的问题。
阅读全文
相关推荐
![hpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)