代码之家  ›  专栏  ›  技术社区  ›  elFreak

为什么使用“this”指针来调用派生成员函数?

  •  4
  • elFreak  · 技术社区  · 7 年前

    在阅读关于虚拟函数的教程(与本例无关)时 this

    class Weapon
    {
        public:
          void features()
             { cout << "Loading weapon features.\n"; }
    };
    
    
    
    class Bomb : public Weapon
    {
        public:
           void features()
             { 
                this->Weapon::features(); 
                cout << "Loading bomb features.\n"; 
             }
    };
    

    为什么用“this”指针调用函数Weapon::features()?这不是已经暗示了吗?

    1 回复  |  直到 6 年前
        1
  •  4
  •   Stephan Lechner    7 年前

    这个 this 是隐式给出的,是否显式地写常常是风格的问题。在你的情况下,我认为这并不能提高可读性。

    然而,在其他情况下,显式地编写代码是有意义的,甚至是必要的

    class SomeClass {
    public:
        void print(int amount) const {
            cout << amount << endl;
        }
        int amount = 10;
    };
    
    int main() {
        SomeClass c;
        c.print(20);
    }
    

    输出为 20 ,如果要访问数据成员,则必须写入 cout << this->amount << endl 有时甚至是必须的。