私人成员与私人继承

  • I have a class A that I can not edit:
class A{
public:
    int thisCoolFuntion(){
        return 0;
    }
};
  • I want to create a class that uses thisCoolFuntion() (let's call it class B or C)
  • I want the user to be able to create an instance of B or C, but that he doesn't have access to thisCoolFuntion().

  • I thought one solution was to do a private inheritance:

class B : A{
public:
    int member;
    void setBMember(){
    member = thisCoolFuntion();
    }
};
  • I also thought on having a private member of type A:
class C{
    A memberA;
    int member;
public:
    void setCMember(){
        member = memberA.thisCoolFuntion();
    }
};
  • 这两种解决方案似乎有效:
int main(int argc, const char * argv[]) {
    // insert code here...
    B b;
    b.setBMember();
    //b.thisCoolFuntion(); --> Error!
    C c;
    c.setCMember();
    //c.memberA.thisCoolFuntion(); --> Error!
    return 0;
}

问题:我应该如何比较这2个解决方案?我该如何选择最适合我的项目的?是其中之一更快吗?还是需要更多的内存?是用户更普遍认可的一种方法吗?

评论