C++如何在子类中覆盖方法

发布于 2025-02-05 13:59:48 字数 880 浏览 5 评论 0原文

我有一些我试图上班的代码,我对如何执行此操作的其他建议愿意。基本上,我有一些基础课,我想要一堆子类要继承。然后,我的功能需要调用此方法的子类版本。

#include <iostream>

using namespace std;

//my base class
class BaseClass {
    public:
    void myMethod(){
        std::cout  << "Base class?" << std::endl;
    }
};

/my subclass
class SubClass1: public BaseClass{
    public:

    void myMethod(){
        std::cout << "Subclass?" << std::endl;
    }
};

//method that I want to call SubClass.myMethod(). I cannot declare this as
//SubClass1 because there will be multiple of these.

void call_method(BaseClass object){
    return object.myMethod();
}


int main()
{
    BaseClass bc;
    SubClass1 sb1;

    //works how I expect it to
    sb1.myMethod();
    //I want this to also print "Subclass?"
    //but it prints "Base class?".
    call_method(sb1);



    return 0;
}

感谢您的帮助

I have some code I'm trying to get to work, I'm open to other suggestions on how to do this. Basically, I have some base class that I want a bunch of subclasses to inherit. I then have a function that needs to call the subclass version of this method.

#include <iostream>

using namespace std;

//my base class
class BaseClass {
    public:
    void myMethod(){
        std::cout  << "Base class?" << std::endl;
    }
};

/my subclass
class SubClass1: public BaseClass{
    public:

    void myMethod(){
        std::cout << "Subclass?" << std::endl;
    }
};

//method that I want to call SubClass.myMethod(). I cannot declare this as
//SubClass1 because there will be multiple of these.

void call_method(BaseClass object){
    return object.myMethod();
}


int main()
{
    BaseClass bc;
    SubClass1 sb1;

    //works how I expect it to
    sb1.myMethod();
    //I want this to also print "Subclass?"
    //but it prints "Base class?".
    call_method(sb1);



    return 0;
}

Thanks for your help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小伙你站住 2025-02-12 13:59:48

您需要将基类中的成员函数声明为虚拟。例如

virtual void myMethod() const {
    std::cout  << "Base class?" << std::endl;
}

,在派生类中覆盖它

void myMethod() const override {
    std::cout << "Subclass?" << std::endl;
}

,函数call_method必须具有一个代表对基类对象的参考的参数

void call_method( const BaseClass &object){
    object.myMethod();
}

You need to declare the member function in the base class as virtual. For example

virtual void myMethod() const {
    std::cout  << "Base class?" << std::endl;
}

And in the derived class to override it

void myMethod() const override {
    std::cout << "Subclass?" << std::endl;
}

And the function call_method must have a parameter that represents a reference to base class object

void call_method( const BaseClass &object){
    object.myMethod();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文