C ++:使用前向类声明的main()中的含义

时间:2016-01-30 13:21:48

标签: c++ forward-declaration

我有三个C ++类:Position,Employer和Person。每个人都有雇主和就业岗位。如下所示,我使用前向类声明将Employer和Position类加入Person类。

我是新的转发类的声明,但发现When to use forward declaration帖子对何时以及如何使用前向声明非常有见地。

但是,我主要关注如何在我的main函数中使用setPosition()?

person.h

class Position;
class Employer;

class Person
{
public:
    // other public members
    void setPosition(Employer* newC, Position* newP)
    {
        m_position = newP;
        m_employer = newC;
    }
private:
    // other member variables
    Position* m_position;
    Employer* m_employer;
};

以下是 main.cpp

的摘要
#include "employer.h"
#include "person.h"
#include "position.h"

int main()
{
    Employer StarFleet("StarFleet Federation", "space exploration");
    Person JLP("Jean-Luc Picard");
    Position cpt("StarFleet Captain", "Save the world");

    JLP.setPosition(StarFleet,cpt);

    return 0;
}

问题是获得编译错误:

  

错误:没有匹配函数来调用' Person :: setPosition(Employer&,Position&)'在main.cpp中   候选人是:   void Person :: setPosition(Employer *,Position *)

     

来自'雇主'的参数1没有已知的转换。到雇主*'

我想知道如何在main()中使用setPosition?

我希望我已经说清楚了。如果您需要我的更多代码,请告诉我。

1 个答案:

答案 0 :(得分:7)

您的函数参数是指针,但您可以按值发送变量。您必须使用他们的地址:

JLP.setPosition(&StarFleet,&cpt);