2013-05-10 51 views
1

我试图解决我有关C++类的问题。为了防止复杂的问题,我会为我的问题写一个示例代码。现在,这是我的问题。C++定义一个类到另一个类

class sample1 
{ 
public: 
//getter,setter,constructor and destructor functions 
private: 
string label; 

} 

class sample2 // in sample2.h #include "sample1" is exist. 
{ 
public: 
    //getter setter constructors and destructors. 
    void addSample1(string label); 
private: 
    vector<sample1*> sample1's; 
} 

现在,您可以看到,我想用sample1指针在sample2类中填充矢量。我试图用下面的代码做到这一点,但显然矢量只能存储一个指针,因为在实现addSample1函数后,指针丢失了。这里是我的代码,它不起作用。

void addSample1(string label) 
{  
     sample1 samp1(label); 
    sample1 * n_pointer=new samp1(label); 
    n_pointer=&samp1; 
    sample1's.push_back(n_pointer); 
} 

有没有人可以帮助我解决我的问题?在此先感谢

+0

你的意思是'向量',对吧? – tadman 2013-05-10 21:16:24

+0

@tadman是啊,你是完全正确的,对于语法错误抱歉,这只是我的问题的一个例子 – 2013-05-10 21:17:06

+0

发布代码时,请提供编译代码。它只是让事情变得混乱,当你有撇号字符变量的变数 – 2013-05-10 21:44:05

回答

5

addSample应该只是:

void addSample1(string label) 
{  
    sample1s.push_back(new sample1(label)); 
} 

,你将不得不小心并删除这些指针一旦你与他们做或存储智能指针在向量中。

你在做什么addSample真的很糟糕。

void addSample1(string label) 
{  
    // creates a local sample1 object on the stack 
    sample1 samp1(label); 
    //creates a sample1 object on heap 
    sample1 * n_pointer = new sample1(label); 
    // overwrites the sample1 pointer with the address of the local object 
    // this will leak memory as you have lost the pointer to the dynamically allocated object. 
    n_pointer=&samp1; 
    //pushes the pointer that points to the local object into the vector 
    sample1s.push_back(n_pointer); 

    // here the local object is destroyed so now the pointer in the vector 
    // points to deallocated space, accessing it will result in undefined behaviour 
} 
+0

,对不起, ılkdefa goruyorum boylebırseyı – 2013-05-10 21:25:54

+0

'new sample1(label)'分配并创建一个新的sample1对象。将它放在推动中只是将该指针添加到向量的末尾。 – 2013-05-10 21:31:29

+0

非常感谢,我意识到我的重大错误,非常感谢 – 2013-05-10 21:46:17

1

怎么样

void addSample1(string label) 
{  
    sample1's.push_back(new sample1(label)); 
} 
1

这应该工作:

void sample2::addSample1(string label) 
{  
    sample1* n_pointer=new sample1(label); 
    sample1s.push_back(n_pointer); 
} 

重命名您的成员变量:

private: 
    vector<sample1*> sample1s;