【CPP】调用父类的重写方法
【CPP】调用父类的重写方法
在C++中,如果你有一个子类重写了父类的方法,你可以通过以下几种方式调用父类的重写方法:
1. 使用作用域解析运算符 ::
你可以使用作用域解析运算符 :: 来显式调用父类的方法。
class Parent {
public:
    void print() {
        std::cout << "Parent class" << std::endl;
    }
};
class Child : public Parent {
public:
    void print() {
        std::cout << "Child class" << std::endl;
    }
    void callParentPrint() {
        Parent::print();  // 显式调用父类的print方法
    }
};
int main() {
    Child child;
    child.print();         // 调用子类的print方法
    child.callParentPrint(); // 调用父类的print方法
    return 0;
}
2. 通过父类指针或引用调用
如果你有一个指向子类对象的父类指针或引用,你可以通过该指针或引用调用父类的方法。
class Parent {
public:
    virtual void print() {
        std::cout << "Parent class" << std::endl;
    }
};
class Child : public Parent {
public:
    void print() override {
        std::cout << "Child class" << std::endl;
    }
};
int main() {
    Child child;
    Parent* parentPtr = &child;
    parentPtr->print();  // 调用子类的print方法,因为print是虚函数
    // 如果你想调用父类的print方法,可以使用作用域解析运算符
    parentPtr->Parent::print();  // 显式调用父类的print方法
    return 0;
}
3. 在子类方法中调用父类方法
在子类的方法中,你可以直接使用 Parent::methodName() 来调用父类的方法。
class Parent {
public:
    void print() {
        std::cout << "Parent class" << std::endl;
    }
};
class Child : public Parent {
public:
    void print() {
        Parent::print();  // 调用父类的print方法
        std::cout << "Child class" << std::endl;
    }
};
int main() {
    Child child;
    child.print();  // 先调用父类的print方法,再调用子类的print方法
    return 0;
}
总结
- 使用 Parent::methodName()可以在子类中显式调用父类的方法。
- 如果父类的方法是虚函数,通过父类指针或引用调用时会调用子类的重写方法,除非显式指定父类的作用域。
- 在子类的方法中,你可以选择性地调用父类的方法,并在其前后添加子类的特定逻辑。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号