gpt4 book ai didi

c++ - 在 C++ 文档教程的这个示例中,为什么指针声明了两次?

转载 作者:太空宇宙 更新时间:2023-11-04 14:55:33 25 4
gpt4 key购买 nike

我正在学习 C++ 文档教程,但在理解这个在构造函数中使用指针的示例时遇到了一些困难:

// example on constructors and destructors
#include <iostream>
using namespace std;

class CRectangle {
int *width, *height;
public:
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
};

CRectangle::CRectangle (int a, int b) {
width = new int;
height = new int;
*width = a;
*height = b;
}

CRectangle::~CRectangle () {
delete width;
delete height;
}

int main () {
CRectangle rect (3,4), rectb (5,6);
cout << "rect area: " << rect.area() << endl;
cout << "rectb area: " << rectb.area() << endl;
return 0;
}

似乎指针*width被声明了两次。它是在类的最开始声明的:int *width, *height;,也是在构造函数初始化时声明的width = new int;

为什么要声明指针两次?

最佳答案

不,它们只声明一次,并且在构造函数中分配值。

关于c++ - 在 C++ 文档教程的这个示例中,为什么指针声明了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16564920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com