在下面的代码中:
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; x(T);
之类的代码时,才不应该将它交给该运算符吗?但是它的行为就像是一个转换运算符,如何? 最佳答案
mval x; x(T);
与(*this)(*begin);
有何不同?在这两种情况下,我都看到一个mval
类型的对象,后跟带有一个参数的括号。您期望发生什么? (*this)
不是类型,它是mval
类型的左值,所以我也看不到它的“表现如何,就像它是一个转换运算符”。
关于c++ - 关于转换运算符和operator(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35164641/