C ++从另一个类调用函数 [英] C++ Calling a function from another class

查看:175
本文介绍了C ++从另一个类调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对c ++非常新,从另一个类调用一个函数有困难。



B类继承自A类,我希望A类能够调用在B类中创建的函数。

  using namespace std; 

B类;

class A
{

public:

void CallFunction()
{
B b;
b.bFunction();
}

};

class B:public A
{
public:
virtual void bFunction()
{
//这里做的东西
}

};

这一切在屏幕上看起来都不错(没有明显的错误),但是当我尝试编译它,错误C2079'b'使用未定义的类B.



我试过让他们指针/ 朋友

$

  void CallFunction()
{/ /< -----在这一点上,编译器知道
//没有关于B的成员。
b.bFunction();
}

这发生的原因与C中的函数不能调用其中至少有一个被声明为函数原型。



为了解决这个问题,我们需要确保两个类在被使用之前被声明。我们将声明与定义分开。 此MSDN文章更详细地说明了声明和定义。 p>

  class A 
{
public:
void CallFunction
};

class B:public A
{
public:
virtual void bFunction()
{...}
}

void A :: CallFunction()
{
B b;
b.bFunction();
}


Very new to c++ having trouble calling a function from another class.

Class B inherites from Class A , and i want class A to be able to call a function created in class B.

using namespace std;

class B;

class A 
{

public:

    void CallFunction ()
    {
        B b;
        b.bFunction();
    }

};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }

};

It all looks fine on screen (no obvious errors) but when I try to compile it i get an error C2079 'b' uses undefined class B.

I've tried making them pointers/ friends but i'm getting the same error,

解决方案

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

这篇关于C ++从另一个类调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆