注册 登录
编程论坛 C++教室

这段代码clComp起到什么作用?涉及到什么知识点?

hffjhhh 发布于 2021-04-02 21:02, 1768 次点击
在classComp结构中定义了一个operator()函数,结构后面还添加上了clComp,
clComp起到什么作用?涉及到什么知识点?
以及operator()是函数吗?为什么一定要添加operator()?如果是函数为什么后面还有个带2个参数的括号?
代码如下:
struct classComp{
    bool operator()(int i,int j){return(i<j);}
}clComp
4 回复
#2
rjsp2021-04-03 09:44
struct classComp{
    bool operator()(int i,int j){return(i<j);}
}clComp;
等同于
struct classComp{
    bool operator()(int i,int j){return(i<j);}
};
struct classComp clComp;

clComp起到什么作用?涉及到什么知识点?
为什么要定义这个类型,起什么作用应该去问源代码作者呀!

以及operator()是函数吗?为什么一定要添加operator()?如果是函数为什么后面还有个带2个参数的括号?
是个函数名。
为什么要定义这个函数你去问源代码作者。
正因为是函数,所以才要有参数列表呀。

这个函数是个操作符重载,也就是 clComp.operator()(1,2) 可以直接写成 clComp(1,2)

#3
hffjhhh2021-04-03 17:45
回复 2楼 rjsp
如果将clComp改为其它名称cmk可以吗?
struct classComp{
    bool operator()(int i,int j){return(i<j);}
}cmk;

或者放置在function函数后面可以吗?
程序代码:
struct classComp{
    bool operator()(int i,int j){return(i<j);}
}
void function(){};
clComp;

或者改为这样可以吗?
struct classComp{
    bool operator+(int i,int j){return(i<j);}
}clComp;


[此贴子已经被作者于2021-4-3 19:06编辑过]

#4
rjsp2021-04-04 10:01
回复 3楼 hffjhhh
如果将clComp改为其它名称cmk可以吗?
可以,但用到clComp的地方都要改为cmk。

或者放置在function函数后面可以吗?
我之前已经说过了,应该是 struct classComp clComp;

bool operator+(int i,int j){return(i<j);}
加号操作符只有两个参数,你这个包含3个参数了(其中一个是this)。
我都不知道你想问什么。

#5
zbjzbj2021-04-05 18:37
这段代码是给你演示怎么写操作符函数,或者重载操作符。
这一段代码本身很无聊,但是如果你看懂了,你就可以写出操作符函数了。
1