如何通过引用传递对象以供另一个文件使用

时间:2013-12-21 22:43:13

标签: c++ oop parameter-passing pass-by-reference

我想在名为MinPriority.cpp的文件中访问此函数:

MinPriority::priority& MinPriority::HEAP_EXTRACT_MIN(*this) //dequeue's min element of tree
{
    MinPriority::priority& min = heapArray.front();
    heapArray.erase(heapArray.begin());
    MIN_HEAPIFY(0);
    return min;
}

它应该从向量heapArray中取出一个元素,并将对象priority传递给另一个称为Graph.cpp的文件。这是在Graph.cpp中调用函数的地方......

void Graph::MST_PRIM()
{
    MinPriority priority;
    for(unsigned int i = 0; i != adjList.size(); i++)
    {
        priority.createArray(adjList[i].front().m_vertex, *this);
    }
    while(priority.queue_Empty() == false)
    {
        priority& u = priority.HEAP_EXTRACT_MIN(/*...*/); //graph.cpp 88
    }

}

类MinPriority声明为:(为简单起见,草拟它)

class MinPriority
{
private:
    class priority
    {
    public:
        priority(string preVertex, string vertex, int weight)
        {
            m_preVertex = preVertex;
            m_vertex = vertex;
            m_weight = weight;
        }
        ~priority(){}
        string m_preVertex;
        string m_vertex;
        int m_weight;
    };
    vector<priority> heapArray;
public:
        //member functions are included here...
};

基本上,最后,我希望能够从heapArray中弹出东西,将它传递给Graph.cpp中的函数,并可能从Graph.cpp中修改heapArray中的内容。我从不需要将数据结构推送到数据结构,因为它们已经存在(因为函数未显示)。错误:

$ make -f makefile.txt
g++ -Wall -W -pedantic -g -c Graph.cpp
Graph.cpp: In member function `void Graph::MST_PRIM()':
Graph.cpp:88: error: `u' undeclared (first use this function)
Graph.cpp:88: error: (Each undeclared identifier is reported only once for each function it appears in.)
Graph.cpp:88: error: no matching function for call to `MinPriority::HEAP_EXTRACT_MIN()'
MinPriority.h:39: note: candidates are: MinPriority::priority& MinPriority::HEAP_EXTRACT_MIN(MinPriority::priority&)
Graph.cpp: At global scope:
Graph.cpp:97: warning: unused parameter 'vertex'
makefile.txt:9: recipe for target `Graph.o' failed
make: *** [Graph.o] Error 1

1 个答案:

答案 0 :(得分:1)

不确定您要对此代码执行的操作:

 MinPriority::priority& MinPriority::HEAP_EXTRACT_MIN(*this) //dequeue's min element of tree
 {
   MinPriority::priority& min = heapArray.front();
   heapArray.erase(heapArray.begin());
   MIN_HEAPIFY(0);
   return min;
 }

但是你有一些问题:

  1. 该方法没有参数类型,只有*这没有意义。
  2. 您正在返回对临时的引用,这是未定义的行为,可能会崩溃。
  3. 我认为你真正想要的是一个包装器方法来返回deque的前面并删除它:

     MinPriority::priority MinPriority::PopFront()
     {
       // Copy of the front element
       MinPriority::priority min = heapArray.front();
    
       // Remove/destroy the front element
       heapArray.erase(heapArray.begin());
    
       // Return the copy
       return min;
     }