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>


基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 运算符重载的基本规则和习语是什么? 2022-10-31