简体   繁体   English

Forward 声明类的实例

[英]Instance of Forward declared Class

It's the follow up question of this: error C2504 circular inclusion .这是这个的后续问题: 错误 C2504 循环包含 Child if forward declared in parent's header.子如果在父的标头中向前声明。

It is not included, so the complier wont find Child?它不包括在内,所以编译器不会找到孩子? Then how do i instantiate a new Child object from Parent object.那么我如何从父对象实例化一个新的子对象。

Parent.h父.h

#pragma once
#include <vector>

using std::vector;
class Child;
class Parent
{
public:
    Parent();
    void GiveBirth();
    ~Parent();
    vector<Child*> children;
};

Parent.cpp父.cpp

#include "stdafx.h"
#include "Parent.h"


Parent::Parent()
{

}

void Parent::GiveBirth()
{
    Child ch = Child(); //Error: incomplete type is not allowed
}

Parent::~Parent()
{
}

Child.h儿童.h

#pragma once
#include "Parent.h"
class Child : Parent
{
public:
    Child();
    ~Child();
};

Child.cpp子文件

#include "stdafx.h"
#include "Child.h"


Child::Child()
{
}


Child::~Child()
{
}

Here are some reading list for you.这里有一些阅读清单供您阅读。

http://en.wikipedia.org/wiki/Opaque_pointer http://en.wikipedia.org/wiki/Opaque_pointer

http://en.wikibooks.org/wiki/C%2B%2B_Programming/Idioms#Pointer_To_Implementation_.28pImpl.29 http://en.wikibooks.org/wiki/C%2B%2B_Programming/Idioms#Pointer_To_Implementation_.28pImpl.29

Parent.cpp父.cpp

#include "stdafx.h"
#include "Parent.h"
#include "Child.h"


Parent::Parent()
{

}

void Parent::GiveBirth()
{
    //Child ch = Child(); //Error: incomplete type is not allowed
    children.push_back(new Child());
}

Parent::~Parent()
{
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM