The Binding of a Data Member
《深度探索C++对象模型》第三章“Data语意学”
3.1 The Binding of a Data Member
下面一段代码的输出是什么?
[xiaochu.yh@OceanBase cpp]$ cat member_binding.cpp #include <iostream> using namespace std; typedef int len_t; class Point { public: void mum(len_t val) { _val = val; cout << _val << endl; } private: typedef float len_t; len_t _val; }; int main() { Point p; p.mum(123.3); return 0; }
答案是:123
那么下面一段代码呢?
[xiaochu.yh@OceanBase cpp]$ cat member_binding.cpp #include <iostream> using namespace std; typedef int len_t; class Point2 { private: typedef float len_t; public: void mum(len_t val) { _val = val; cout << _val << endl; } private: len_t _val; }; int main() { Point2 p2; p2.mum(123.3); return 0; }
答案是:123.3
从上面的案例中可以知道,作为一种防御性编程风格,建议把类体中的typedef放在最前面,如例2中所示。
还看最后一段代码,会是什么输出呢?
[xiaochu.yh@OceanBase cpp]$ cat member_binding.cpp #include <iostream> using namespace std; class Point { public: void mum(len_t val) { _val = val; cout << _val << endl; } private: typedef float len_t; len_t _val; }; int main() { Point p; p.mum(123.3); return 0; }
答案是:编译失败
member_binding.cpp:7: error: ‘len_t’ has not been declared