【问题标题】:how to call another class's member function?如何调用另一个类的成员函数?
【发布时间】:2022-01-15 16:23:54
【问题描述】:

我有两个类,A类,B类,B类中有一个静态函数,如下所示:

class A {
public:
    void method(){ B::method(); }

};

class B {
public:
    static int method() {
        cout << "method of b" << endl;
    
    }
};

int main()
{
    class A a;
    a.method();
}

此代码构建错误,因为在A类中,B没有被声明,但我希望A类比B类更早定义,我该怎么办?我以为它可能需要前向声明,但似乎不是这个原因......

【问题讨论】:

  • 在定义B后将函数体移出类。
  • "但是我希望 A 类比 B 类更早定义" 为什么?您希望通过这种方式解决什么问题? “我原以为可能需要提前声明,但似乎不是这个原因……” 你为什么这么认为?您如何尝试使用前向声明?当你尝试这样做时发生了什么?

标签: c++ class


【解决方案1】:

看看修改后的代码。内联 cmets 解释了这些变化:

class A { 
public:
    // only declare the method
    void method();
    // Do NOT define it here:
    // { B::method(); }
};

class B { 
public:
    static int method() {
        std::cout << "method of b" << std::endl;
        return 0;
    }   
};

// and now, as B implementation is visible, you can use it.
// To do this, you can define the previously declared method:
void A::method() { B::method(); }

int main()
{
    class A a;
    a.method();
}

提示:请不要使用using namespace std

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多