gpt4 book ai didi

c++ - 结构内重载运算符的调用约定?

转载 作者:行者123 更新时间:2023-11-30 05:14:44 25 4
gpt4 key购买 nike

我在上课前重温了 C++ 中的结构概念,并写下了以下内容:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

struct isOdd{
bool operator()(int x){
return x%2;
}
};

int main(){
vector<int> v {3,4,2,1,65,2,4,65,2,9,8,5,7};

int count = count_if(begin(v), end(v), isOdd());

cout << "size of vector: " <<v.size() << endl;
cout << "count of odds: " <<count << endl;
return 0;
}

然后我意识到在调用结构 isOdd 的函数时,我使用了语法:isOdd() 但我只覆盖了 () 运算符。那么调用约定 isOdd() 是如何工作的,因为调用结构函数就像:结构::函数名();或 structure-object.functions-name();

有人可以详细说明这个疑问吗?

谢谢。

最佳答案

Then I realize that in calling function of structure isOdd, I have used the syntax: isOdd() but I have only overridden the () operator.

不,您调用了隐式编译器生成的 默认构造函数,从而创建了 isOdd 的临时对象。

例如:如果您想在单个数字上测试它而不创建命名的 isOdd 对象,您可以:

bool is_odd = isOdd()(4);
//^^ Creates a temporary object

优化编译器将省略临时对象的创建,因为它既没有可观察到的副作用也没有状态。

关于c++ - 结构内重载运算符的调用约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43343061/

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