如何使方法不可被覆盖

huangapple go评论71阅读模式
英文:

How to make method non-override-able

问题

我正在做作业,需要知道如何(如果可能的话)使基类中的公共方法无法被覆盖。

class base
{
public:
    virtual void bar() = 0;
    void foo()
    {
        //进行一些计算
        this->bar();
    }
}
class der : public base
{
public:
    virtual void bar() {std::cout<<"Bar\n";}

    //我希望防止有人在这里覆盖foo方法
    void foo()
    {
        //进行其他计算
    }
}

我认为你应该能够像这样做,但我不知道如何做,也找不到在线上的相关信息。对于糟糕的英语和可能不正确使用覆盖这个术语,我想要的是不让别人在der类中创建foo方法。

提前感谢。

英文:

I am working on a homework and I need to know how(if possible) to make a public method in the base class non-override-able.

class base
{
public:
    virtual void bar() = 0;
    void foo()
    {
        //Do some calculations
        this->bar();
    }
}
class der : public base
{
public:
    virtual void bar() {std::cout<<"Bar\n";}

    //I want to prevent someone from overriding foo method here
    void foo()
    {
        //Do other calculations
    }
}

I think that you should be able to do something like this but I don't know how and I couldn't find anything about it online. Sorry for bad english and sorry if I misused the term override, what I want is to not let someone make the foo method in the der class.

Thanks in advance.

答案1

得分: 1

任何虚拟方法都可以被声明为最终方法。

struct Base
{
    virtual ~Base() = default;
    virtual void f() = 0; 
    virtual void g() final {} // 这个方法既不能被重写也不能在派生类中被屏蔽
};

struct Derived : Base
{
    void f() final { }
    // void g() {} // 编译错误
};

struct MoreDerived : Derived
{
    // void f() {}; // 编译错误
};
英文:

Any virtual method can be made final.

struct Base
{
    virtual ~Base() = default;
    virtual void f() = 0; 
    virtual void g() final {} //this cannot neither overridden nor shadowed in derived class
};

struct Derived : Base
{
    void f() final { }
    // void g() {} //compile error
};


struct MoreDerived : Derived
{
    // void f() {}; //compile error
};

huangapple
  • 本文由 发表于 2023年4月4日 14:51:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75926294.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定