简体   繁体   English

如何调用另一个班级的成员function?

[英]how to call another class's member function?

I have two class, class A, Class B, in class B has a static function like below: I have two class, class A, Class B, in class B has a static function like below:

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();
}

this code build error, because in class A, B is not be declared, but I want class A be defined earlier than class B, how should i do?此代码构建错误,因为在 class A 中,未声明 B,但我希望 class A 的定义早于 class B,我该怎么办? I was thought it may need forward declaration, but it seems not this reason...我以为它可能需要前向声明,但似乎不是这个原因......

Take a look at the modified code.看一下修改后的代码。 Inline comments explain the changes:内联注释解释了这些变化:

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过将类的对象和成员函数传递给C ++中的另一个函数来调用类? - How do I call a class by passing it's object and member function to another function in c++? 如何从另一个函数调用属于类成员的函数? - How do I call a function that is member of a class, from another function? 我如何获得一个类成员函数来访问另一个类成员函数的私有成员? - How do i get a class member function to have access to another class member function's private member? 如何使用来自另一个 class 的公共成员 function 作为参数调用线程 - How to call thread with a public member function from another class as argument 如何从同一类的另一个成员函数调用函子? - How to call a functor from another member function of the same class? How can I call a non-static member function of a class from a static member function of another class? - How can I call a non-static member function of a class from a static member function of another class? 如何为类成员函数调用函数指针 - How to call function pointer for class member function 您如何在类外部的成员函数中调用成员函数? - How do you call a member function in a member function outside of a class? 从一个 class 访问成员 function 的数据成员到另一个类的成员 function - Access data member of a member function from one class to another class's member function 如何调用与类成员同名的函数 - How to call function with same name as class member
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM