繁体   English   中英

构造函数中的变量未在此 scope c++ 中声明

[英]variable in constructor not declared in this scope c++

请原谅我仍然是 c++ 的初学者 以下代码给出了变量不在 scope 中的错误,

error: 'vec' was not declared in this scope   
         vec[key] = value;

在不改变 object 在主 function 中声明的方式的情况下,我该如何解决这个问题?

// Program to illustrate the working of
// objects and class in C++ Programming

#include <iostream>
#include <vector>
using namespace std;

// create a class
class MyHashMap {
public:
    /** Initialize your data structure here. */
    // vector<int> vec;
    MyHashMap() {
        vector<int> vec(1000000, -1);
    }
    
    /** value will always be non-negative. */
    void put(int key, int value) {
        vec[key] = value;
    }
    
    /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
    int get(int key) {
        return vec[key];
    }
    
    /** Removes the mapping of the specified value key if this map contains a mapping for the key */
    void remove(int key) {
        vec[key] = -1;
    }
};


int main() {
   int key,value;
   cin>>key>>value;
   MyHashMap* obj = new MyHashMap();
   obj->put(key,value);
   int param_2 = obj->get(key);
   obj->remove(key);
   return 0;
}
/** Initialize your data structure here. */
std::vector<int> vec;
MyHashMap():vec(1000000, -1)
{}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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