【问题标题】:How to use a method of a class from a pointer on an instance of this class?如何通过此类实例上的指针使用类的方法?
【发布时间】: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


【解决方案1】:

我会这样做:

type ClassA::do_something_using_a_method_of_class_B() {
  if (!instanceB) throw BadThingHappened();
  return instanceB->method_of_class_B();
}

或者,如果您有合适且良好的类型默认值:

type ClassA::do_something_using_a_method_of_class_B() {
  if (!instanceB) return type{};
  return instanceB->method_of_class_B();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 2012-02-14
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多