C++调用通用基类的私有/受保护函数
下面的示例中有没有一种很好的方式可以从B::bar()
调用A::foo()
?C++调用通用基类的私有/受保护函数
class A {
protected:
void foo() {}
};
class B : public A {
public:
void bar(A& a) { // edit: called with &a != this
a.foo(); // does not work
}
};
我想不出比宣布B
是的A
朋友其它任何东西,但可能变得相当难看多用一些类。
任何想法?
是的,你可以使用一个基类的功能。
class A {
protected:
void foo() {}
void do_other_foo(A& ref) {
ref.foo();
}
};
class B : public A {
public:
void bar(A& a) { // edit: called with &a != this
this->do_other_foo(a);
}
};
当然是在工作。不是很好,但可能是最好的解决方案。谢谢! – 2010-12-20 00:12:49
你为什么要传递类型A的对象?你可以这样做:
class B : public A {
public:
void bar() {
foo();
}
};
,或者类似这样的
class B : public A {
public:
void bar() {
A::foo();
}
};
我并不打算在'* this'上使用'B :: bar',而是在其他实例上(实际上在A的其他子类中)使用'B :: bar'。 – 2010-12-19 21:00:58
@lucas听起来像是一个设计问题。为什么foo()受到保护? – 2010-12-19 21:03:17
看到我上面的帖子,我不想让我的图书馆之外的类/函数使用它。 – 2010-12-19 21:06:26
下面就给人“保护”之类访问,允许通过任何派生类或对象调用的方法。 它使用一个受保护的令牌类型,需要取消锁定特权方法:
struct A
{
protected:
//Zero sized struct which allows only derived classes to call privileged methods
struct DerivedOnlyAccessToken{};
public: //public in the normal sense :
void foo() {}
public: //For derived types only :
void privilegedStuff(DerivedOnlyAccessToken aKey);
};
struct B: A
{
void doPrivelegedStuff(A& a)
{
//Can create a token here
a.privilegedStuff(DerivedOnlyAccessToken());
}
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
a.foo();
a.privilegedStuff(A::DerivedOnlyAccessToken()); // compile error.
B b;
b.doPrivelegedStuff(a);
return 0;
}
这不是我的主意。我读了一些地方。对不起,我不记得那是谁的狡猾想法。
我希望编译器可以忽略aKey参数。
非常好的主意,非常感谢! – 2012-06-24 20:45:29
为什么'B :: bar'需要调用'A :: foo'?如果'A :: foo'受到保护,这应该意味着只有'A'类型的对象和从'A'派生的任何类型才能够调用它。如果你确实需要从一个不相关的类调用'A :: foo',可能它不应该被保护。 – 2010-12-19 20:57:26
什么是问题? – 2010-12-19 20:57:56
当'B'是'A'类型时,将'A'实例传递给'B'的原因是什么? – birryree 2010-12-19 20:58:11