2015-04-06 62 views
0

我需要构建一组相互依赖的类。当我将一个类的指针传递给另一个在其中实例化的类时,我遇到了麻烦。如何取消引用另一个对象内的对象的指针

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

#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; 
} 

你知不知道我是如何实现这些功能的?

预先感谢您

+0

您不能从内联代码中取消引用前向声明。这必须展示给一个单独的翻译单位。 –

回答

0

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

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

0

“你知不知道我怎么做到的,不会发生那些错误?”

这很简单。你省略引用base的内联codeparts和类的完整声明后,移动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; 
}; 

定义功能后,基地被充分地宣称:

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

int main() { 
    base b1; 

    system("pause"); 
    return 1; 
}