英文:
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
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论