gpt4 book ai didi

c++ - 关于转换运算符和 operator()

转载 作者:搜寻专家 更新时间:2023-10-31 00:58:37 24 4
gpt4 key购买 nike

在下面的代码中:

template <class T> class mval {
protected:
T max;
public:
template <class iter> mval (iter begin, iter end):max(*begin) {
while(begin != end) {
(*this)(*begin);
++begin;
}
}
void operator()(const T &t) {
if (t > max)
max = t;
}
void print() {
cout << max;
}
};

int main() {
int arr[3] = { 10,20,5 };
(mval<int>(arr, arr + 3)).print();
}

为什么 (*this)(*begin); 会导致 operator()

它不应该只在你有像mval x这样的东西时才转到这个运算符(operator)那里吗? x(T); ?但它的行为就像一个转换运算符,怎么样?

最佳答案

mval x 怎么样? x(T);(*this)(*begin); 有什么不同?在这两种情况下,我都看到一个 mval 类型的对象,后面跟着一个括号,里面有一个参数。你期望发生什么? (*this) 不是类型,它是 mval 类型的左值,所以我也看不出它如何“表现得像一个转换运算符”。

关于c++ - 关于转换运算符和 operator(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35164641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com