How to use Class Prototype in C++

2019-05-24 07:30发布

I'm trying to create class Object before defining class. Here is the example.

class A;
class B;

class A{
    public: 
    void fun(B obj){
    }
};
class B{ };
int main(){

    return 0;
}

Here is the Error List:

In member function 'void A::fun(B)':
6   13  [Error] 'obj' has incomplete type
2   7   [Error] forward declaration of 'class B'

Any Solution? I already Searched about it, but failed to solve this.. Thanks in Advance.

3条回答
贼婆χ
2楼-- · 2019-05-24 08:03

Provide A::fun()'s definition out-of-line, after B has been fully declared :

#include <iostream>

class A;
class B;

class A {
    public: 
    void fun(B obj);
};

class B{ };

void A::fun(B obj) {}

int main() {
    return 0;
}

The definition wil typically go into a .cpp file, where you'd include B.h to have its complete declaration.

Also, please don't using namespace std;.

查看更多
欢心
3楼-- · 2019-05-24 08:04

At this point:

void fun(B obj) {
}

the compiler needs to know what B is. That is, how big it is, what types its members have, what constructors are defined, etc. Otherwise, it can't generate the code you're asking it to.

You can work around this by:

  1. defining (not declaring) B before A, or
  2. only declare A::fun inline, and move the definition after B has also been defined
  3. pass B obj by pointer or reference - because pointers and references are all the same size, and neither invoke constructors you haven't declared yet, this works, but ... you still can't do anything with the B instance in fun until B has been defined.

    So, the current code will compile, but it will break again if fun does anything more than pointer arithmetic.

查看更多
劳资没心,怎么记你
4楼-- · 2019-05-24 08:07

In this function definition,

void fun(B obj){
}

you're telling the compiler that you are going to pass an instance of B on the stack to fun. The compiler therefore needs to know the definition of B so that it knows how much stack space to allocate. At this point in the code, you have only declared that B exists. You have not provided it a definition of B, so it can't know how much memory is required.

[Edited to fix the declaration/definition misstatement]

查看更多
登录 后发表回答