得到的函数没有返回我期望的东西

时间:2015-07-23 20:06:07

标签: c++ arrays function pointers c++11

我正在尝试在我的类中创建一个get函数来返回它将获取i,j参数并返回位于Object(i,j)的值。

到目前为止,在我的get函数中,它将i,j转换为1d数组中的等价物i *(列数)+ j,在我的代码中等于5。 接下来,我想显示数组中位置5的值。但它似乎返回我的数组的第一个值,而不是位置5的值。我有什么想法我错了?我是以错误的方式使用指针吗?我的完整计划如下:

 #include <iostream>
    using namespace std;

    class MyMatrix{

    public:
        //default constructor set member variables to null states
        MyMatrix();
        MyMatrix(int sizeR, int sizeC, double * input_data);        
        ~MyMatrix();    //destructor

        //member functions
        int get(int i, int j);

    private:
        int m;      //rows
        int n;      //columns
        double * data;
    };

    int main(){

        const int rows = 3;
        const int columns = 2; 
        double * userInput;

        cout << "The array is 3*2, or 6 elements." << endl;

        userInput = new double[rows*columns];
        double temp;
        for (int i = 0; i < rows*columns; i++){             //let the user type in the array
            cout << "Please enter value" << i << endl;
            cin >> temp;
            *(userInput + i) = temp;
        }

        MyMatrix ObjectA(rows, columns, userInput); //creating object with specifications
        cout << "The value of ObjectA 2,1 is: " << ObjectA.get(2, 1) << endl;


        return 0;
    }

    MyMatrix::MyMatrix(){
        cout << "MyMatrix constructor lets go" << endl;
        m = 0;
        n = 0;
        data = 0;
    }

    MyMatrix::MyMatrix(int sizeR, int sizeC, double * input_data){
        cout << "MyMatrix::MyMatrix(int sizeR, int sizeC, double * input_data) is called." << endl; //Showing the constructor working :)
        m = sizeR;
        n = sizeC;

        data = new double[m*n];
        for (int i = 0; i < m*n; i++){
            data[i] = *input_data;
        }

        cout << "The items you have entered are:" << endl;      //printing out array showing the array is filled
        for (int i = 0; i < m*n; i++){
            cout << i << "item is: " << *(input_data + i) << endl;
        }
    }

    int MyMatrix::get(int i, int j){
        cout << "getFunction is happening" << endl;

        //val should just be K  [K = i * N + j]
        int val = 0;
        val = i * n + j;        //n is COLUMNS, m is ROWS derp
        cout << "val is equal to: " << val << endl; //so val would be 5
        //how do i get it to display what is at location 5 in object A

        return data[val]; // shouldnt this return the 5th element in data?
    }


    MyMatrix::~MyMatrix(){
        cout << "MyMatrix::~MyMatrix() is invoked" << endl; //showing DESTRUCTA function is working
        delete[] data;  //the memory management 

    }

1 个答案:

答案 0 :(得分:0)

使用3.times do puts "I'm a refactoring master!" end 代替data[i] = input_data[i],并添加data[i] = *input_data以释放内存,否则会导致内存泄漏。

相关问题