【问题标题】:C++ access my vector in another headerfile and cppC++ 在另一个头文件和 cpp 中访问我的向量
【发布时间】:2016-07-29 21:25:35
【问题描述】:

如何从 aHisto.h 访问我在 aDie.h 中声明的向量,最好不要作为函数访问?一旦我的向量在我的 Histo.h 中,我希望能够对其进行修改、更改大小,并按照我的选择进行操作。我只是在 VS 中遇到错误消息。

aDie.h

    #define aDie_H   
    #pragma once
    #include <vector>
    #include <iostream>
    class aDie {
    public: 
        aDie();
        void numRolls();
        void getSeed();
        void roll(); 
        void myVector(); //just gives my vector values
        void Print(); 
        std::vector<int> myV; //declare my vector, it has values stored from void myVector();

    private: 
        int i = 0;
        int Rolls;
        int dSeed;
        int die1;  
        int die2;
        int sum; 

    }; 

aHisto.h

#define aHistogram_H 
#include "aDie.h" 

class aHistogram : public aDie{
public: 
//adds a pointer to my vector so I can access and modify it anywhere on this header
    aHistogram();   //default const
    void getVector(); //does stuff with vector

private: 
    int i = 0;
    int min;
    int max; 
};

aHisto.cpp

#include "aHistogram.h"  
#include "aDie.h"
#include <iostream>   
#include <vector>
using namespace std;

aHistogram::aHistogram() { //default constructor 
    min = 0;
    max = 0; 

}   
void aHistogram::getVector() {

//does stuff with vector here

    }

【问题讨论】:

  • 您可以使用aDie::myV 访问它,究竟有什么问题?你尝试了什么?为什么它对你不起作用?
  • 每个继承类都有自己的父类变量的副本,因此您应该能够使用this-&gt;myV 甚至只是myV 访问它。
  • 你怎么打电话给myVector()等等?你的main 和其他相关方法是什么样的?

标签: c++ class vector header


【解决方案1】:

使用范围解析运算符,因为aHistogram 继承自aDie

或者由于继承访问级别,您可以使用this

void aHistogram::getVector() {
      aDie::myV->something();
      //Or use this pointer
      this->myV->something();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    相关资源
    最近更新 更多