我目前正在学习C++,并且遇到了这个让我很困惑的地方。我有一节课:
class MyClass {
public:
std::map<int,int> *myMaps;
}我如何解除myMaps的引用?这不管用。
int main() {
MyClass *test = new MyClass();
std::map<int,int> *testMap = new std::map<int,int>();
(*testMap)[1] = 1;
test->myMaps = testMap;
std::cout << *test->myMaps[1] << std::endl;作为后续,如果我在地图中有一张std地图,以及如何取消它呢?
class MyClass {
public:
std::map<int,std::maps<int,int>> *myMaps;
}发布于 2021-12-06 22:55:28
,我怎么解除
myMaps的引用?
就像取消引用任何其他指针一样。与您在(*testMap)[1] = 1;中所做的完全一样
,这是行不通的。
不,不是,但这确实是:
test->myMaps = testMap;
std::cout << (*(test->myMaps))[1] << std::endl;
// or cleaner:
// std::cout << (*test->myMaps)[1] << std::endl;
// due to operator precedence...在对取消引用的map::operator[]对象调用std::map之前,请注意指针周围的额外括号。
作为后续,如果我在地图中有一个std地图,以及如何取消引用呢?
首先取消引用myMaps (如上面所示),然后按键访问内部映射,就像按键访问任何值一样,例如:
(*(test->myMaps))[1][2] = ...;
//(*test->myMaps)[1][2] = ...;
cout << (*(test->myMaps))[1][2];`
//cout << (*test->myMaps)[1][2];`话虽如此,我们根本没有理由使用指向std::map的指针。用这个代替:
class MyClass {
public:
std::map<int,int> myMaps;
};
int main() {
MyClass test;
std::map<int,int> testMap;
testMap[1] = 1;
test.myMaps = std::move(testMap);
// or, prior to C++11:
// test.myMaps.swap(testMap);
std::cout << test.myMaps[1] << std::endl;
}class MyClass {
public:
std::map<int,std::map<int,int>> myMaps;
};
int main() {
MyClass test;
std::map<int,std::map<int,int>> testMap;
testMap[1][2] = 1;
test.myMaps = std::move(testMap);
// test.myMaps.swap(testMap);
std::cout << test.myMaps[1][2] << std::endl;
}https://stackoverflow.com/questions/70252877
复制相似问题