【发布时间】:2018-01-07 14:55:01
【问题描述】:
我有一个班级ClassA 和一个班级ClassB.
InClassAone of the data members is a pointer on an instance ofClassB.
I want to define a method inClassAthat uses a method of the instance ofClassB`,我该怎么做?
hpp 文件
class ClassA
{
public:
type ClassA::do_something_using_a_method_of_class_B();
private:
ClassB* instanceB;
}
class ClassB
{
public:
type ClassB::method_of_class_B();
}
cpp 文件
type ClassA::do_something_using_a_method_of_class_B()
{
return instanceB.method_of_class_B();
}
【问题讨论】:
-
我会这样做:
type ClassA::do_something_using_a_method_of_class_B() { if (!instanceB) throw BadThingHappened(); return instanceB->method_of_class_B(); } -
确实有效,请将其作为答案,以便我接受。
标签: c++ class inheritance polymorphism