如何在另一个类头文件中定义类构造函数?

gam*_*n67 3 c++ constructor header-files

这是一个基本问题,但让我很难过。我有类A并且在头文件中我想B从另一个头文件定义另一个类构造函数。我在下面尝试了这段代码,我确定这不是正确的方法。

class A{
public:
    A();
    B b();  //Constructor from another Class that defined in another header file
    void Operation();
};
Run Code Online (Sandbox Code Playgroud)

我需要调用构造函数BA.h这样我就可以在构造函数B内部调用构造函数A,也可以在 Class Binside 中使用函数A::Operation()

A.cpp

#include "A.h"
#include "B.h"
A::A{
    b();  //call constructor b
}

void A::Operation(){
    b.someFunction();  //use function from class B, error here
}
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,我得到的错误是 b.someFunction()

表达式必须具有类类型

任何人都知道如何在另一个类头文件中正确定义另一个类的构造函数?并在主类构造函数中调用另一个构造函数并全局使用另一个类的函数?对不起,基本和令人困惑的问题。

Mic*_*ler 5

This is not a constructor:

class A{
public:
    A();
    B b();  //This is a function named b, returning an object of type B
    void Operation();
};
Run Code Online (Sandbox Code Playgroud)

Same here:

A::A{
    b();  //call function b from above, that returns a B object
}
Run Code Online (Sandbox Code Playgroud)

And same here:

void A::Operation(){
    b.someFunction();  // Without invoking method b, you apply the dot operator on the method - which is illegal.
}
Run Code Online (Sandbox Code Playgroud)

You probably want an object of type B, and call someFunction method on it. Maybe you want:

class A{
public:
    A();
    B b; // this is object named b, of type B
    void Operation();
};
Run Code Online (Sandbox Code Playgroud)

And then, if the constructor of B requires parameters, you can:

A::A () : b(constructor parameters) {
}
Run Code Online (Sandbox Code Playgroud)

If there is no need to pass parameters, you can just omit the construction of b, and the language will simply use the default constructor of B (without parameters).

A::A ()  {
}
Run Code Online (Sandbox Code Playgroud)