语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。
下面, 我们来看看C++中运算符的重载:
- #include <iostream>
- using namespace std;
-
- // 复数类
- class C
- {
- private:
- int x;
- int y;
-
- public:
- C()
- {
- x = 0;
- y = 0;
- }
-
- C(int xx, int yy)
- {
- x = xx;
- y = yy;
- }
-
- // 只考虑x 和 y都是非负整数
- void print()
- {
- if(0 == x && 0 == y)
- {
- cout << 0 << endl;
- }
- else if(0 == y)
- {
- cout << x << endl;
- }
- else if(0 == x)
- {
- cout << "j" << y << endl;
- }
- else
- {
- cout << x <<" + j" << y << endl;
- }
- }
-
- // 利用成员函数重载复数的 +=
- void operator+=(const C& c)
- {
- x += c.x;
- y += c.y;
- }
- };
-
- int main()
- {
- C c1(1, 1);
- c1.print();
-
- C c2(2, 2);
- c2.print();
-
- c2.operator += (c1); // operator += 其实就是函数名
- c2.print();
-
- c2 += c2; // 语法糖:运算符重载了, 好看了, 但功能一样
- c2.print();
-
- int i = 1;
- int j = 2;
- j += i;
- cout << j << endl;
-
- c1 + c2; // error, 未定义行为
-
- return 0;
- }
语法糖, 好甜
我们知道, 成员函数可以直接访问私有的数据成员, 友元函数也能, 故上面程序可以改为:
- #include <iostream>
- using namespace std;
-
- // 复数类
- class C
- {
- private:
- int x;
- int y;
-
- public:
- C()
- {
- x = 0;
- y = 0;
- }
-
- C(int xx, int yy)
- {
- x = xx;
- y = yy;
- }
-
- // 只考虑x 和 y都是非负整数
- void print()
- {
- if(0 == x && 0 == y)
- {
- cout << 0 << endl;
- }
- else if(0 == y)
- {
- cout << x << endl;
- }
- else if(0 == x)
- {
- cout << "j" << y << endl;
- }
- else
- {
- cout << x <<" + j" << y << endl;
- }
- }
-
- friend void operator+=(C& c1, const C& c2);
- };
-
- // 利用友元函数重载复数的 +=
- void operator+=(C& c1, const C& c2)
- {
- c1.x += c2.x;
- c1.y += c2.y;
- }
-
- int main()
- {
- C c1(1, 1);
- c1.print();
-
- C c2(2, 2);
- c2.print();
-
- operator += (c1, c2); // operator += 其实就是函数名
- c1.print();
-
- c1 += c1; // 语法糖:运算符重载了, 好看了, 但功能一样
- c1.print();
-
- int i = 1;
- int j = 2;
- j += i;
- cout << j << endl;
-
- c1 + c2; // error, 未定义行为
-
- return 0;
- }