Cast vectorlt;Tgt; to vectorlt;const Tgt;(投射向量lt;Tgt;到向量lt;const Tgt;)
问题描述
我有一个类型为 vector<T>
的成员变量(其中 T 是自定义类,但也可以是 int.)我有一个函数,我想从中返回指向该向量的指针,但我不希望调用者能够更改向量或其项.所以我希望返回类型是 const vector<const T>*
I have a member variable of type vector<T>
(where is T is a custom class, but it could be int as well.)
I have a function from which I want to return a pointer to this vector, but I don't want the caller to be able to change the vector or it's items. So I want the return type to be const vector<const T>*
我尝试过的所有铸造方法都不起作用.编译器一直抱怨 T 与 const T 不兼容.
None of the casting methods I tried worked. The compiler keeps complaining that T is not compatible with const T.
这里有一些代码演示了我正在尝试做的事情的要点;
Here's some code that demonstrates the gist of what I'm trying to do;
vector<int> a;
const vector<const int>* b = (const vector<const int>* ) (&a);
此代码无法为我编译.
提前致谢!
推荐答案
如果你有一个 const vector
你不能修改容器,也不能修改容器中的任何元素.您不需要 const vector<const int>
来实现这些语义.
If you have a const vector<int>
you cannot modify the container, nor can you modify any of the elements in the container. You don't need a const vector<const int>
to achieve those semantics.
这篇关于投射向量<T>到向量<const T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:投射向量<T>到向量<const T>


- OpenGL 对象的 RAII 包装器 2021-01-01
- XML Schema 到 C++ 类 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- GDB 不显示函数名 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 如何提取 __VA_ARGS__? 2022-01-01
- DoEvents 等效于 C++? 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01