gpt4 book ai didi

c++ - 从作为指针的类成员获取值

转载 作者:行者123 更新时间:2023-11-30 00:57:29 24 4
gpt4 key购买 nike

给定以下代码:

#include <iostream>
using namespace std;

class CRectangle {

public:
int *width, *height;
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;

CRectangle * p = new CRectangle(10,10);

cout << "rect area: " << p->*height << endl;

return 0;
}

如何让最后的 cout 语句生效?

最佳答案

移动解引用运算符。 p->height 指的是整型指针height。然后将 * 放在前面取消引用 int 指针。

cout << "rect area: " << *p->height << endl;

关于c++ - 从作为指针的类成员获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7988489/

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