【问题标题】:C++ primitive array accessing by class按类访问 C++ 原始数组
【发布时间】:2023-03-11 18:45:01
【问题描述】:

我想使用类访问原始类型数组。 我正在使用 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 中可能吗?

【问题讨论】:

  • 你想使用你的类对象作为索引吗?为什么?
  • CInt 类背后的目的是什么?它应该解决什么问题?
  • 至于您的问题如何您是如何实现intsize_t 运算符的?您可以尝试创建一个Minimal, Complete, and Verifiable Example 来展示给我们看吗?此外,在将 MCVE 添加到您的问题时,请包括您可能遇到的错误。
  • 可能重复:How cast C++ class to intrinsic type。虽然你没有提供minimal reproducible example,所以无法真正分辨
  • 我们应该猜测错误吗? “不起作用”是什么意思?来人吧

标签: c++ class indexing


【解决方案1】:

我怀疑你有一个错误,不是因为你的班级,而是你在哪里做数组分配。您必须在函数内进行数组赋值:(这应该可以工作,假设您正确重载了转换运算符)

arr[index] = 2; // ERROR! <-- you can't do this outside a function 

int main() {
    arr[index] = 2; // <-- must be within a function

【讨论】:

    【解决方案2】:

    你是如何重载 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;
    }
    

    【讨论】:

    • 好吧,我错了!也很抱歉不完整的问题/错误报告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 2015-12-13
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    • 1970-01-01
    • 2021-04-30
    相关资源
    最近更新 更多