学了一小段时间CPP,果然像大家说的那样,CPP的语法设计真的很糟糕。
看如下代码:
1 #include <iostream> 2 3 using namespace std; 4 5 class Foo { 6 private: 7 int x; 8 int y; 9 public: 10 Foo(); 11 Foo(int x, int y); 12 ~Foo(); 13 void setX(int x); 14 void setY(int y); 15 int getX(); 16 int getY(); 17 }; 18 19 Foo::~Foo() 20 { 21 cout << "a Foo instance is dead" << endl; 22 } 23 24 Foo::Foo() 25 { 26 cout << "create a Foo instance" << endl; 27 } 28 29 Foo::Foo(int x, int y) 30 { 31 this->x = x; 32 this->y = y; 33 cout << "create a Foo instance and initialize it" << endl; 34 } 35 36 void 37 Foo::setX(int x) 38 { 39 this->x = x; 40 } 41 42 void 43 Foo::setY(int y) 44 { 45 this->y = y; 46 } 47 48 int 49 Foo::getX() 50 { 51 return this->x; 52 } 53 54 int 55 Foo::getY() 56 { 57 return this->y; 58 } 59 60 int 61 main(void) 62 { 63 // 创建初始化 64 Foo f2 = Foo(3, 4); 65 Foo f(3, 4); // f(3, 4) 可以 f()是不可以的,看下面。 66 67 // 创建不初始化 68 Foo foo2 = Foo(); 69 // Foo foo3(); // 这个是失败的,编译器会认为是函数申明, 而不是创建foo3这个变量。 70 Foo foo1; 71 72 cout << f.getX() << ", " << f.getY() << endl; 73 cout << f2.getX() << ", " << f2.getY() << endl; 74 return 0; 75 }
我们根据Foo f(3, 4);调用了 Foo::Foo(int, int)创建实例, 会认为Foo foo(); 可以调用Foo::Foo()创建实例。 这就造成了语义的二义性。
不过编译器避免这个问题还是比较简单的,知道C的人一看Foo f(); 肯定知道这是函数申明!
版权声明
本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者Saturn和本文原始地址:
https://ndtm-idea.blogspot.com/2013/07/projectscpptestindent.html
0 comments:
Post a Comment