【问题标题】:Creating Two Array of Pointers of Custom Objects that Contain the same object (same pointer) in corresponding indices创建两个在相应索引中包含相同对象(相同指针)的自定义对象指针数组
【发布时间】:2022-01-08 10:46:39
【问题描述】:

我正在尝试创建两个对象数组,这样如果我更改数组的一个元素,它应该反映在第二个数组中(基本上是两个对象指针数组,在每个相应的索引中具有相同的指针)

代码如下:

#include <iostream>
using namespace std;

class A{
  private:
    int n;
    
  public:
    A(int num){
      n = num;
    }
    void print(){
      cout << n;
    }
};

int main() {
  A** a = new A*[5];
  A** b = new A*[5];

  for(int i=0; i< 5; i++){
    int n;
    cout << "Enter a number: ";
    cin >> n;
    A obj(n);
    a[i] = &obj;
    b[i] = &obj;
  }

  // all the elements of these arrays are the last number entered by user
  for(int i=0; i< 5; i++){
    a[i]->print();
    cout << " "; 
    b[i]->print();
    cout << endl;
  }
  
  // because they point to the same memory location
  for(int i=0; i< 5; i++){
    cout << a[i] << " " << b[i] << endl;
  }
} 

输出如下:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
5 5
5 5
5 5
5 5
5 5
0x7fff6ee63530 0x7fff6ee63530
0x7fff6ee63530 0x7fff6ee63530
0x7fff6ee63530 0x7fff6ee63530
0x7fff6ee63530 0x7fff6ee63530
0x7fff6ee63530 0x7fff6ee63530

我想要什么输出:

Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
1 1
2 2
3 3
4 4
5 5
some_memory_address_1 some_memory_address_1
some_memory_address_2 some_memory_address_2
some_memory_address_3 some_memory_address_3
some_memory_address_4 some_memory_address_4
some_memory_address_5 some_memory_address_5

我知道是这种情况,因为 C++ 使用在 for 循环内定义的 n 相同的内存位置,但我怎样才能避免这种情况并获得我想要的结果?

【问题讨论】:

  • 你需要使用new来分配对象。 A obj(n); 在 for 循环中只存在到迭代结束然后它被销毁并且你有悬空指针。
  • A** a = new A*[5]; 在 C++ 中是迟钝的。简单的A* a[5]; 对于一个简单的本地小数组就足够了。事实上,由于您不需要处理多态性或需要交换元素,因此您可以完全避免需要存储指针:A a[5];(但您需要定义一个默认构造函数)。似乎根本不需要b 数组。

标签: c++ arrays object


【解决方案1】:

两个对象数组,如果我改变一个数组的元素,它应该反映在第二个数组中

您可以创建一个实际的数组(存储、数组所有者)并通过两个数组引用来使用它:

#include <iostream>
#include <span>
#include <vector>

struct A { int n; }; // your class, simplified for the example

int main() {
    std::vector storage(5, A{}); // the array
    std::span a{storage}, b{storage}; // the references to the array
    a[0].n = 42; // mutate the array
    std::cout << a[0].n << ' ' << b[0].n << '\n'; // observe the mutation via array references
    std::cout << a[1].n << ' ' << b[1].n << '\n'; // untouched elements are untouched
}

您的用例的完整代码(A 仍被简化):

#include <iostream>

int main() {
    struct { int n; } storage[5];
    auto &a = storage, &b = storage;
    for (auto& element: a) std::cout << "Enter a number: ", std::cin >> element.n;
    for (std::size_t i{}; i < std::size(a); ++i) std::cout << a[i].n << ' ' << b[i].n << '\n';
    for (std::size_t i{}; i < std::size(a); ++i) std::cout << &a[i].n << ' ' << &b[i].n << '\n';
}

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2018-08-25
    • 1970-01-01
    • 2016-03-08
    • 2018-06-23
    • 2015-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多