C++学习记录-面向对象-运算符重载6-函数调用运算符即括号重载

一、

重载函数调用运算符,即重载括号,可以实现 对象( ) 语法时进行一些操作,即可以像函数一样使用对象

二、语法及示例

语法: 返回值(一般为void) operator()( 参数列表) { 方法 };

如:

1
2
3
4
5
6
void operator()(chara& a)
{
owner = a.name;
a.weap = name;
cout << "为" << a.name << "装备" << name << endl;
}

示例:

先创建两个类:

1
2
3
4
5
6
7
8
9
10
11
class chara {
public:
string name;
string weap = "新手武器";

public:
chara(string a)
{
name = a;
}
};
1
2
3
4
5
6
7
8
9
10
11
class weapon {
public:
string name;
string owner;

public:
weapon(string a)
{
name = a;
}
}

然后在weapon类中重载函数调用运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class weapon {
public:
string name;
string owner;

public:
weapon(string a)
{
name = a;
}

//重载函数调用运算符
void operator()(chara& a)
{
owner = a.name;
a.weap = name;
cout << "为" << a.name << "装备" << name << endl;
}//实现了将weapon装备到chara上
};

进行操作:

1
2
3
4
5
6
7
8
9
10
11
void test()
{
//先创建两个对象
chara qyn("琪亚娜");
weapon thsc("天火圣裁");

//使用刚刚重载的函数调用符号
thsc(qyn);

cout << qyn.weap << endl;
}

运行结果:

为琪亚娜装备天火圣裁
天火圣裁
D:\Work\C艹练习\练手\Project1\Debug\Project1.exe (进程 45920)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .