c++ 将 2D 数组分配给对象
c++ assign a 2D array to an Object
我的代码通过了编译器,但我对指针的概念有疑问。
主.cpp:
int main(int argc, const char * argv[])
{
int inputPuzzle[3][3];
std::cout << "Set the puzzle: " << "n";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cin >> inputPuzzle[i][j];
}
}
puzzle puzzle_1 = *new puzzle(inputPuzzle);
puzzle_1.display();
return 0;
}
拼图.h:
class puzzle
{
public:
puzzle();
puzzle(int [][maxCol]);
~puzzle();
public:
int puzz [maxRow][maxCol];
};
拼图.cpp:
puzzle::puzzle(int a[][maxCol])
{
for (int i = 0; i < maxRow; i++) {
for (int j = 0; j < maxCol; j++) {
puzz[i][j] = a[i][j];
}
}
}
我的问题是关于声明的:puzzle puzzle_1 = *new puzzle(inputPuzzle);
为什么我必须在要在其中分配 2D 数组的新对象前面添加"*"?
您正在C++编程,其中new
返回一个指针。当你使用星号时,它是取消引用运算符,基本上将指针变成非指针。
像这样使用 取消引用运算符意味着您实际上会丢失 new
创建的指针,并且您无法释放分配的内存delete
这当然会导致内存泄漏。
为了避免丢失指针,您必须将变量声明为指针:
puzzle* puzzle_1 = new puzzle(inputPuzzle);
然后,在访问成员时,您必须改用指针成员选择器运算符:
puzzle_1->display();
而且,为了避免泄漏内存,当您完成指针时,您必须delete
它:
delete puzzle_1;
但是,在C++中,很少需要使用指针;而只是将其声明为普通变量:
puzzle puzzle_1(inputPuzzle);
puzzle_1.display();
与您的问题无关,但如果maxRow
或maxCol
大于 3
,那么您将从内存外部读取数组inputPuzzle
。这将导致未定义的行为。
这里最重要的部分是new
关键字。它返回指向新实例化对象的指针。检查动态内存分配以获取更多信息,并了解何时以及如何使用指针,以及 new
关键字的工作原理。
现在,我们知道 new
关键字返回一个指针,并且您希望获取一个对象而不是指针,因此您必须取消引用您的指针。
现在有两个正确的解决方案:
// without pointers
puzzle puzzle_1(inputPuzzle); // initialize the object without going through a copy
puzzle_1.display();
// with pointers
puzzle *puzzle_1 = new puzzle(inputPuzzle);
puzzle_1->display(); //notice that we used -> here as it's a pointer
// do stuffs here
delete puzzle_1; // free the memory
相关文章:
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 为什么我可以在不重载 "=" 运算符的情况下将一个对象分配给另一个对象?
- 为对象分配整数.输出将是什么?
- C++ 使用枚举类对象分配 std::map 值
- 如何在C++中为增加但记住删除先前对象的对象分配唯一标识符
- 我重载了 << 和 = 运算符。为什么当我将一个对象分配给另一个对象并尝试打印它时,我会被打印出来?
- 为什么将两个对象分配给另一个对象后,两个对象不一样?
- 有没有办法在同名类 (c++) 中为对象分配一个指针变量
- 如何使用函数(而不是构造函数)将派生类对象分配给基类指针
- 是否可以使用 malloc 为类对象分配内存?
- 将对象分配给数组C++
- 我们可以在cpp中为对象分配函数吗
- 为模板参数类型中的新对象分配内存
- 我无法将对象分配给对象数组
- 对象分配-成员函数的使用无效错误
- 将派生对象分配给函数内的基类指针
- Arduino ESP32如何将BLEUUID对象分配到字符串中
- Rapidjson将密钥值从一个文档对象分配到另一个文档对象
- 奇怪的对象分配行为C