从另一个类c ++中获取值

时间:2015-04-30 05:20:42

标签: c++ constructor

你好我在adjacencyMatrix类中有一个getter

int AdjacencyMatrix::getVertexFirst() const {   return vertexFirst; }

和构造函数

AdjacencyMatrix::AdjacencyMatrix() {
    this->vertexCount=0;
    this->vertexFirst=0;
    this->edgeCount=0;
    this->matrix=0;
    this->wage=0;

}

bool AdjacencyMatrix::createFromFile(string path) {
    fstream file;
    file.open(path.c_str(), fstream::in);
    if (file.good())
    {
        int vertexF,vertexE,wag;            
        file >> this->edgeCount;
        file >> this->vertexCount;
        file >> this->vertexFirst;      

        matrix = new int *[vertexCount];
        wage   = new int *[vertexCount];

        for (int i = 0; i < vertexCount; i++)
        {
            matrix[i]=new int[vertexCount];
            wage[i]=new int[vertexCount];
        }

        //fill matrix by zeros
        for (int i = 0; i < vertexCount; i++)
        {

            for(int j=0; j<vertexCount;j++)
            {
                matrix[i][j]=0;
                wage[i][j]=0;

            }

        }  

        // fill matrix by 1

        for(int i=0; i<edgeCount; i++)
        {
            file >> vertexF >> vertexE >> wag;
            this->matrix[vertexF][vertexE]=1;
            this->wage[vertexF][vertexE]=wag;

        }    
        file.close();
        return true;
    }

    return false;
}

当然打印在Adjacency类中工作 现在我希望在Dijkstra类

中拥有这个值
//Dijkstra.cpp    
#include "Dijkstra.h" 
AdjacencyMatrix am;

bool Dijkstra::makeDijkstraAlgo() {     
    int vertexCount=am.getVertexCount();    
    int vertexFirst=am.getVertexFirst();
    int **wage=am.getWage();    
    cout << vertexCount;    
    cout << vertexFirst;
 .......... }

这是我的主要课程

#include <iostream>
#include "Dijkstra.h"
#include "Screen.h"
using namespace std;

int main() {
    AdjacencyMatrix am; 
    Dijkstra dijkstra;

    am.createFromFile("matrix.txt");
    dijkstra.makeDijkstraAlgo();
    dijkstra.viewDijkstra();
    return 0;
}

并且此cout仅显示0,但在AdjacencyMatrix中显示正常值。你能帮助我吗 ?

更新

我注意到总是0,因为我在构造函数中初始化了.... 那么如何制作这样的东西

我从文件创建一个矩阵,并将值添加到vertexCount等。

am.createFromFile("matrix.txt");

现在我想从邻接矩阵类到Dijkstry类得到这个值(vertexCount等)并生成

dijkstra.makeDijkstraAlgo();
dijkstra.viewDijkstra();

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您正在创建一个矩阵但使用另一个矩阵。

makeDijkstraAlgo使用名为“am”的全局矩阵,但main有自己的同名矩阵。

摆脱全局并将main的矩阵传递给函数

bool Dijkstra::makeDijkstraAlgo(const AdjacencyMatrix& am) {     
    int vertexCount=am.getVertexCount();    
    int vertexFirst=am.getVertexFirst();
    int **wage=am.getWage();    
    cout << vertexCount;    
    cout << vertexFirst;
    // ...
}

int main() {
    AdjacencyMatrix am; 
    Dijkstra dijkstra;

    am.createFromFile("matrix.txt");
    dijkstra.makeDijkstraAlgo(am);
    dijkstra.viewDijkstra();
    return 0;
}