【问题标题】:How can I change the "x"th value to "y"?如何将第 \"x\" 个值更改为 \"y\"?
【发布时间】:2022-11-20 02:14:24
【问题描述】:
#include <iostream>
using namespace std;
class IntArray {
private:
    int* m_data;
    int m_len;
public:
    IntArray(int = 0, int = 0);
    ~IntArray();
    void print(void);
    
    void set(int x, int y) {//!!!
        int temp = x

        x = y;
        y = temp;
    }
};
IntArray::IntArray(int size, int init) {
    if (size <= 0) {
        m_data = nullptr;
        m_len = 0;
    }
    else {
        m_data = new int[size];
        m_len = size;
        for (int idx = 0; idx < m_len; ++idx)
            *(m_data + idx) = init;
    }
}
IntArray::~IntArray() {
    delete[]m_data;
}
void IntArray::print(void) {
    for (int idx = 0; idx < m_len; ++idx)
        cout << *(m_data + idx) << ' ';
    cout << std::endl;
}
int main() {
    cout << "a1: ";
    IntArray a1{ 10, 100 };
    a1.print();
    cout << "a2: ";
    IntArray a2{ a1 };
    a2.set(3, 999);
    a2.set(9, 123);
    a2.print();
    return 0;
}

当我输出 a2 时,我想在第三个输出“999”,在第九个输出“123”,在其余的输出“100”。但是,使用我编写的代码,只打印了“100”。我该如何解决?
输出

a1: 100 100 100 100 100 100 100 100 100 100
a2: 100 100 100 100 100 100 100 100 100 100

预期的

a1: 100 100 100 100 100 100 100 100 100 100
A2:100 100 100 999 100 100 100 100 100 123

【问题讨论】:

    标签: c++ pointers


    【解决方案1】:

    这是一个提示。让我们看看你的set 方法:

        void set(int x, int y) {
            int temp = x
    
            x = y;
            y = temp;
        }
    

    上面只接受一对参数,xy。交换这些值当地的变量,但实际上并没有改变正在调用的 IntArray 类实例的任何内容。你期望发生什么?

    这是另一个提示。您的 print 方法枚举了 m_data 中的值。也许这是 set 真正应该做什么的线索。

    TLDR:您的 set 方法需要将 y 的值应用到索引为 x 的 m_data。在访问 m_data 之前,它还应该验证 x 是否小于 m_len。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      相关资源
      最近更新 更多