如何取消引用另一个对象内的对象的指针

时间:2015-04-06 14:39:19

标签: c++ class dereference

我需要构建一组彼此依赖的类。当我将指向一个类的指针传递给在其中实例化的另一个类时,我遇到了麻烦。

这里有一个例子来说明我的问题。

#include<iostream>
#include<vector>

using namespace std;

class base;

//

 child class
    class child
    {
    public:
    child(){};
    void setPointer (base* ptr){pointer = ptr; }
    void printing(){(*pointer).print();} // error C2027: use of undefubed type base
                                        // error C2227: '.print' must have class/struct/union
private:
    base* pointer;
};

// base class
class base
{
public:
    base()
    {
        initial_vec();
        VEC[0].setPointer(this);
        VEC[0].printing();
    }

    void print() { cout <<"printing from BASE"<< endl;}

    void initial_vec ()
    {
        child child1;
        VEC.push_back(child1);
    }

private:
    vector<child> VEC;
};

int main()
{
    base b1;

    system("pause");
    return 1;
}

你知道如何在没有出现这些错误的情况下实现这一目标吗?

提前谢谢

2 个答案:

答案 0 :(得分:0)

看起来你得到它的错误是因为你试图只用前向声明从你的printing()类中调用base。要解决您的问题,请在完全定义printing()类后定义函数base的正文。

Here是关于前方声明的更多细节。

答案 1 :(得分:0)

  

&#34;您是否知道如何在不收到错误的情况下实现这一目标?&#34;

这很简单。您省略了引用base的内联代码部分,并在完全声明该类之后移动tem:

#include<iostream>
#include<vector>

using namespace std;

class base;

 child class {
    public:
    child(){};
    void setPointer (base* ptr); // <<< Only declare the functions here
    void printing();

private:
    base* pointer;
};

// base class
class base {
public:
    base()
    {
        initial_vec();
        VEC[0].setPointer(this);
        VEC[0].printing();
    }

    void print() { cout <<"printing from BASE"<< endl;}

    void initial_vec ()
    {
        child child1;
        VEC.push_back(child1);
    }

private:
    vector<child> VEC;
};

在完全声明base之后定义函数:

void child::setPointer (base* ptr){pointer = ptr; }
void child::printing(){(*pointer).print();}

int main() {
    base b1;

    system("pause");
    return 1;
}