类的成员函数中可以直接访问本类形参的私有变量

    技术2022-05-20  53

    刚才在看《c++沉思录》, 对下面这段代码产生疑问:

    class VehicelSurrogate { public: //.... VehicleSurrogate(const VehicelSurrogate & ); //.... private: Vehicle * vp; }; VehicelSurrogate::VehicelSurrogate (const VehicelSurrogate & v) : vp(v.vp ? v.vp->copy() : 0) {}

    之前一直以为类的成员函数的中对于访问本类形参的操作必须通过本类定义的成员函数。但是在上面的例子中,形参v确直接访问了它的私有变量。为了验证这种写法是否可行,编写一个小程序进行验证。程序如下:

    /* * File: scope.cpp */ class Int { public: Int() : value(0) {} Int(int val) : value(val) {} Int(const Int & x); ~Int() {} Int & operator=(const Int & x); private: int value; }; Int::Int(const Int & x) { value = x.value; } Int & Int::operator=(const Int & x) { if (this != &x) value = x.value; return *this; } int main() { Int a(1); Int b; b = a; }

    编译运行,并调试:

    supertool@supertool-desktop:~/test$ c++ -Wall -g scope.cpp -o scope supertool@supertool-desktop:~/test$ ./scope supertool@supertool-desktop:~/test$ gdb ./scope GNU gdb (GDB) 7.1-ubuntu Copyright (C) 2010 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /home/supertool/test/scope...done. (gdb) l 20 Int & Int::operator=(const Int & x) 21 { 22 if (this != &x) 23 value = x.value; 24 return *this; 25 } 26 27 int main() 28 { 29 Int a(1); (gdb) l 30 Int b; 31 32 b = a; 33 } (gdb) b 32 Breakpoint 1 at 0x400635: file scope.cpp, line 32. (gdb) r Starting program: /home/supertool/test/scope Breakpoint 1, main () at scope.cpp:32 32 b = a; (gdb) s Int::operator= (this=0x7fffffffe230, x=...) at scope.cpp:22 22 if (this != &x) (gdb) s 23 value = x.value; (gdb) print value $1 = 0 (gdb) print x.value $2 = 1 (gdb) n 24 return *this; (gdb) print this $3 = (Int * const) 0x7fffffffe230 (gdb) print *$3 $4 = {value = 1} (gdb)

    通过上面的程序验证,这种写法是可行的。起码目前我的编辑器没有报错。在这里,可能把上面这种情况与子类只能访问父类共有和保护成员约定混淆了。至于更进一步的探讨,有待进一步的研究。


    最新回复(0)