Abstract
本章主要介绍了一些类的使用方法,包括:
- 运算符重载
- 友元函数
- 转化函数
1. 运算符重载
1.1 概念
运算符重载是 C++ 多态(polymorphic)的一种形式,其本质上还是函数调用,目的是方便程序员编程,而在汇编层面与普通的函数调用没有太大的区别。
Below 是一个简单的例子,这个对于函数只是进行了 declaration 而没有 relevant definition,so 我们只能够进行编译而不能链接。
// we assume that there is a class named AClass, and it possess a method called operator+
class AClass {
public:
// fishwheel just declare the operator but not define it
AClass operator+(AClass &);
};
int main(){
AClass clsA, clsB;
// be careful the += and + is not a same operator
clsA = clsA + clsB;
return 0;
}
Above の 例子中的clsA = clsA + clsB;
实际上等同于clsA = clsA.operator+(clsB);
When Compiler 解析时,就会按照这种成员函数调用的方式进行。
Let’s see a look what 发生 when 编译结束。
- x86代码
输入下面的命令在 VS 控制台中,可以编译得到一个 x86版本的 .obj 文件。
:: the /c is compile only not linked, and
:: /Od is disable the optimal
cl /c /Od FWTest.cpp
使用 IDA 将其打开,可以看到一个函数名 ??HAClass@@QAE?AV0@AAV0@@Z
,这个就是该类的一个 operator+ 运算符重载了。IDA 在一旁的注释中也给出了相应的 demangling,我们也可以在 VS 控制台中解析这个名字。
可以使用 VS 自带的 undname 来将 MSVC 编译器创建的 C++ 名称粉碎还原 back。
undname ??HAClass@@QAE?AV0@AAV0@@Z
- x64代码
在 x64 native 的 VS 控制台中输入同样的命令,编译得到一份 x64 的 .obj 文件,使用 IDA 打开查看,可以看到??HAClass@@QEAA?AV0@AEAV0@@Z
。这个与 x86 生成的名字是 not 同じ。
继续使用 undname 来解析名称粉碎,可以看到调用约定(calling convention)这一块的部分是不同的。这里 fishwheel 认为是 undname 是存在错误的,x64 的调用约定只有一种,MSDN x64 calling convention,中将其描述为 __vectorcall,でも,when 你使用 IDA 逆向时,你需要将其设置为 __fastcall,which is also 使用 the 寄存器来传递参数。
1.2 可重载运算符
fishwheel 认为这个表的意义不是特别大,既然 this table on the book,我就把它誊抄到自分自身的 Blog 中了,以便日后我会查阅。
+ | - | * | / | % | ^ |
---|---|---|---|---|---|
& | | | ~= | ! | = | < |
> | += | -= | *= | /= | %= |
^ = | &= | |= | << | >> | >>= |
<<= | == | != | <= | >= | && |
|| | ++ | – | , | ->* | -> |
() | [] | new | delete | new [] | delete [] |
1.3 重载限制
- 重载后的运算符必须 at least have 一个 operand 是类型定义 by 用户。so 不能将减法运算符 - 重载为计算两个 double 值的和,rather than 它们的差。
- 使用重载的运算符 can’t violate original 运算符的语法 rule。For example,お前は不能将模运算符(%)重载为 only 使用一个 operand。In the meantime,the privilege of 运算符不能被改变。
- 不能创建新的运算符。例如,不能 like python 那样,使用 operator**() 来表示求幂。fishwheel 认为这是很合理的,运算符的语法解析 depends on 编译器,however,编译器没有关于 operator**() 的语法定义。当然你 urgently want to 用这个,可以考虑更改编译器的实现标准,でも 这是天方夜谭 for 私たち,普通的程序员。
- 不能重载下面的运算符。
- sizeof:sizeof 运算符
- .:成员运算符
- .*:成员指针运算符
- :::作用域解析运算符
- ?::条件运算符
- typeid:一个 RTTI(Run Time Type Identification)运算符
- const_cast:强制类型转换运算符
- dynamic_cast:强制类型转换运算符
- reinterpret_cast:强制类型转换运算符
- static_cast:强制类型转换运算符
- Below の 运算符只能在通过成员函数进行重载
- =:赋值运算符
- ():函数调用运算符
- []:下标运算符
- ->:指针访问类成员运算符
2. 友元函数
2.1 存在意义
As we all know,C++ 控制 access of Object private member。Usually,public method 提供了唯一的访问方式,でも,sometimes 这种限制 so strict that 一些特定的问题无法解决。In this condition,C++ 提供了另一种形式的访问权限:友元(friend),友元有 3 种:
- 友元函数
- 友元类
- 友元成员函数
In this chapter,主要介绍的是 友元函数,主要使用在需要重载 二元运算符 时
2.2 一个问题
继续使用 1.1 中的例子,现在有一个新的需求 AClass 类需要完成与 int 类型的 operator+ 运算。
// we assume that there is a class named AClass, and it possess a method called operator+
class AClass {
public:
// fishwheel just declare the operator but not define it
AClass operator+(AClass &);
// the add operator with int, we don't care the implement
AClass operator+(int);
};
int main(){
AClass clsA, clsB;
int nA;
// this is valid
clsA = clsA + nA;
// this is invalid
//clsA = nA + clsA;
return 0;
}
那么这样就会出现 一个问题,由于 int 不是 AClass 类,所以没有相应的重载函数,导致clsA = clsA + nA
可以转换为 clsA.operator+(nA);
是合法的操作,而 clsA = nA + clsA
无法转化为相应的成员函数。
When this time,我们就可以定义一个 友元 函数来解决这个问题。
// we assume that there is a class named AClass, and it possess a method called operator+
class AClass {
public:
// fishwheel just declare the operator but not define it
AClass operator+(AClass &);
// the add operator with int, we don't care the implement
AClass operator+(int);
// define a friend function
friend AClass operator+(int, AClass &);
};
int main(){
AClass clsA, clsB;
int nA;
// this is valid
clsA = clsA + nA;
// having friend, this is valid
clsA = nA + clsA;
return 0;
}
2.3 创建友元函数
- 将 友元函数 放入到类的 declaration 中,并在其前面添加 friend 关键字进行修饰。
- 友元函数 不是类的成员函数,因此不能使用成员运算符进行调用,但是其与成员函数拥有同じ权限。
- 1.1例子中的友元函数定义如下:
// it's not a member of a class so can't use the AClass::operator+
AClass operator+(int nA, AClass &clsB) {
...
}
2.4 常用友元
When using C++, the usual I/O method is std::cin and std::cout,因此最常用到的两个运算符重载就是 << 和 >> 。
我们 wish 下面的语句能够自动的输出 what we want,而不需要就行更多的格式设置。
AClass clsA
std::cout << clsA;
那么这里就只能使用 友元 函数了,不然我们的输出语句就得是会 like 这样:
// very strange, isn't it?, if don't override it as a member function
clsA << std::cout;
下面给出一个重载 << 进行输出的标准格式:
ostream& operator<<(ostream& os, const AClass& clsA) {
...
return os;
}
几点注意事项如下:
- 函数的返回值必须是 ostream&,这样才能够保证
cout << nA << clsA << endl;
这样语句的连贯性。 - 对于需要输出的类 AClass 尽量使用 const 引用 这样能提高参数传递效率。
- 对于 inherit from ostream 的类都可以作为 参数0 进行使用。
// ofstream inherit from ostream
ofstream fout;
fout.open("");
// use ofstream as the parameter 0
fout << AClass;
- 尽管上面使用了 ostream 类,但是由于没有访问其中的私有数据,所以不用将该声明添加到 ostream 类中;でも,使用了 AClass 类的数据,故要将其添加到 AClass 类的声明中。
3. 转化函数
3.1 类型转化
C++ 中对于 compatible 类型会进行自动的转化,比如 double 和 int 之间。However,对于不兼容的类型是不会进行自动转化的。比如 int * p = 10
这条语句在 C++ 中是无法通过编译的,でも,in C 这条语句是可以编译通过的。这就是 C++ 和 C 之间的存在一点小小的兼容性不一致,which 会导致 if 君は直接将 .c 文件改成 .cpp ,会出现编译错误。
如果我们将int * p = 10
改为 int * p = (int*)10
那么 C++ 和 C 的编译器都能够通过编译(这里我们只考虑 syntax 正确性,而不考虑 semantics)。
让我们回到类里面,对于类来说我们 wish it 能够进行双向的转化,即其他类型能够转化为 class 类型; class 类型能够转化为其他类型。前者一般使用 construct 函数而后者则使用 转换函数。
3.2 其他类型到 class
书上的例子对于一个没接触过英制单位的人来说太抽象了,我决定使用 hour 和 minute 之间的类来 demonstrate。
// FWTime save the time in two different metric
class FWTime {
enum {hour_per_min = 60}; //minute per hour
double hours; //time in hour
int mins; //time in minute
public:
FWTime(double hours);
FWTime(int mins, double hours);
FWTime();
};
有了上述的代码之后就可以直接将 double 的值直接赋值给 FWTime。
FWTime clsTime1; //create a FWTime object
clsTime1 = 19.6; //use the FWTime(double) to convert 19.6 to FWTime
只有接受一个参数的 construct 函数才能够作为 转换函数。下面的 construct 函数有两个参数因此不能够用来转换类型。
FWTime(int mins, double hours); // not a conversion function
however, 如果给第二个参数提供默认值,则可以用于转化 int
FWTime(int mins, double hours = 0); //int-to-FWTime conversion
Using construct 函数作为自动转换函数 seems like a 不错特性。然后,当 Programmer 拥有更丰富经验时,will 发现这种自动特性并非 always 符合需求,it’s because unexpected 转化可能会发生。so C++ 增加了关键字 explicit 用于关闭这种自动特性。
explicit FWTime(double hours); //no implict conversions allowed
上面这样定义只是将 implicit 的自动转化关闭,但是 explicit 的强制转化还是可以被允许的。
FWTime clsTime1; // create a FWTime object
clsTime1 = 19.6 // not valid if FWTime(double) is declared as explicit
clsTime1 = FWTime(19.6);// ok, an explicit coversion
clsTime1 = (FWTime)19.6;// ok, old form for explicit typecast
3.3 class 到其他类型
In 3.2 中可以将数字转为 FWTime 对象,现在我们需要考虑将 FWTime 转化为数字。就 like below 这样的语句:
FWTime clsTime2(3.5);
double flA = clsTime2;
Construct 函数只能够用于从其他类型转化到 class 类型。要进行 contrary 转化就 have to use 特殊的 C++ 运算符函数——转换函数。
如果定义了从 FWTime 到 double 的转化函数,那么 below 的用法就都是可行的。
FWTime clsTime2(3.5);
double flA = double(clsTime2); //syntax #1
double flB = (double)clsTime2; //syntax #2
double flC = clsTime2; //implicit use of conversion function
转化函数的一般格式如下
operator typeName();
需要注意:
- 转换函数 必须是类 method
- 转换函数 不能有返回值
- 转换函数 不能有参数
在 FWTime 中可以定义这样的转换函数。
// FWTime save the time in two different metric
class FWTime {
enum {hour_per_min = 60}; //minute per hour
double hours; //time in hour
int mins; //time in minute
public:
FWTime(double hours);
FWTime(int mins, double hours);
FWTime();
// conversion function
operator int();
operator double();
};
Just like the 显示转化设定,对于 class 到其他类型也可以取消 implicit 的自动转化。只需要在前面添加 explicit 关键字。
explicit operator int();
explicit operator double();
3.4 友元函数和转换函数
如果我们 wish 将 FWTime 与 double 相加,定义了如下 operator+ 重载:
// now only below operator+ override
FWTime operator+(FWTime&, FWTime&);
但我们 want 完成这样的操作:
FWTime clsTime1;
double flA;
clsTime1 = flA + clsTime1; //double + FWTime
那么在我们面前就有两个方式来完成这个任务
- 不重载新的 operator+ 进行参数的匹配,而写 转换函数 使得 double 能够转换为 FWTime when compiling。
- Override 一个新的 operator+ 使其与参数能够 match。
这两种方案各有利弊
- 第一种方法使得程序更简短,the work programmer 要做的就少了,但是每次都会调用转换 construct 函数增加了运行时的时间开销;
- 第二种方案会使得程序较长,the work programmer 要做的就多了,但运行时的消耗就少了。
All in all, 如果程序需要 经常 将 FWTime 与 double 相加,则采取第二种方案,这样对于程序的性能影响 slightly。On the contrary,如果相加机会较少,这采取第一种方案,减少不必要的 work。