a way in c++ to hide a specific function

2020-01-31 20:48发布

i have an inheritance struct A : public B, i want to hide individual functions from B, is this possible?

i know the opposite is possible using using BMethod in the A declaration.

cheers

10条回答
Deceive 欺骗
2楼-- · 2020-01-31 21:15

Can't alter the visibility of the original method.

You could create a method in struct A with the same name and have that method be private, but that doesn't prevent the method from being called when an instance of struct A is being referenced by a variable of type B.

查看更多
3楼-- · 2020-01-31 21:18

If you want to selectively hide functions from B it does not make much sense to use public inheritance in the first place.
Use private inheritance & selectively bring methods from B into the scope of A:

struct B{
   void method1(){};
   void method2(){};
};
struct A : private B{
   using B::method1;
};

A a;
a.method1();
a.method2(); //error method2 is not accesible
查看更多
做自己的国王
4楼-- · 2020-01-31 21:18

There is yet another approach.

class A{
    void f1();
    void f2();
    void f3();
}

class BInterface{
    void f2();
    void f3();
}

class B : public A, BInterface
{
}

BInterface b = new B();
b->f1(); //doesn't work since f1 is not declared in BInterface
b->f2(); //should work
b->f3(); //should work
delete(b);

Use BInterface as a filter for inherited classes to exclude undesirable methods. Liskov Substitution principle isn't violated in this case since an object of BInterface class is not an object of A class even though that an object of B class is an object of BInterface class.

查看更多
放荡不羁爱自由
5楼-- · 2020-01-31 21:18

Why don't you make it Virtual in the base class and override it in its Children? (more help)

查看更多
登录 后发表回答