C++类访问的基元数组

C++ primitive array accessing by class

本文关键字:数组 访问 C++      更新时间:2023-10-16

我想使用类访问基元类型数组。 我正在使用 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;
}