简体   繁体   中英

C++ Accessing class variable from another class

I have a class called MineData:

class MineData {
private:
    int row = 10;
    int col = 20;
public:
    MineData() {
        std::vector<std::vector<int>> data (col, std::vector<int>(row, 0));
    }
}

and I have a class called Grid:

class Grid : public QWidget {
    MineData mineData;
    QPushButton *btn = new QPushButton(mineData.data, this);
}

so I want to access the data variable in Grid class from MineData class, but when I do

mineData.data

I get an error:

class 'MineData' does not have 'data' member

What am I doing wrong?

You have currently declared data as a local variable in MineData 's constructor. Instead, you need to make it a member variable. Then, you can instantiate it in the initializer list.

class MineData {
private:
  int row = 10;
  int col = 20;

public:
  vector<vector<int>> data;
  MineData(): data(col, vector<int>(row, 0)) { }
};

The vector data needs to be added as a class field. Now it is constructed in the MineData class constructor as a temporary variable and it is removed after the constructor function is finished.

class MineData {
private:
    int row = 10;
    int col = 20;
public:
    MineData() {
        data.resize(col, std::vector<int>(row, 0)); 
    }
std::vector<std::vector<int>> data 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM