C++类访问的基元数组
C++ primitive array accessing by class
我想使用类访问基元类型数组。 我正在使用 Visual C++ 2013
class CInt
{
public:
CInt() { val_ = 0; }
CInt(int x) { val_ = x; }
private:
int val_;
};
int arr[2];
CInt index;
arr[index] = 2; // ERROR!
我试图重载 size_t(( 运算符,但仍然不起作用。 在 C++/C++11 中可能出现这样的事情吗?
我怀疑你有一个错误,不是因为你的类,而是你在哪里做数组分配。您必须在函数中执行数组赋值:(假设您正确地重载了转换运算符,这应该有效(
arr[index] = 2; // ERROR! <-- you can't do this outside a function
int main() {
arr[index] = 2; // <-- must be within a function
你是如何重载 size_t(( 运算符的?以下内容对我有用:
#include <iostream>
class CInt
{
public:
CInt() { val_ = 0; }
CInt(int x) { val_ = x; }
operator size_t() const { return val_; }
private:
int val_;
};
int main() {
int arr[2];
CInt index;
arr[index] = 2;
// output: 2
std::cout << arr[index] << std::endl;
}
相关文章:
- 将静态字符数组中的字符分配给动态分配的字符数组 - 访问冲突
- 从数组访问SDL_Rect成员时垃圾值?
- 从 C++ 中的 int ** 数组访问元素
- 使用动态数组访问冲突写入位置
- 如何使用对象数组访问类中的变量?
- 从链表数组访问节点数据
- 返回类型的数组访问
- 在 C++ 中使用指针的数组:访问返回的数组时出现分段错误
- 为什么2D数组访问要比1D阵列访问更快
- 指向数组访问的指针上的隔离错误
- C 通过对象的指针数组访问对象方法
- C 通过数组访问多个成员
- C++可变参数模板数组/访问元素
- 数组访问导致空指针取消引用
- 无法从类数组访问数组
- 为什么编译器允许越界数组访问,即使使用 constexpr 索引也是如此
- C++ 从数组访问重载构造函数
- 为什么为了简单的数组访问,我必须在g++中打开优化
- 如何在重载数组访问运算符时访问SIMD矢量元素
- C++大型2D数组访问冲突