给出以下代码:
#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++ - 从作为指针的类成员获取值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7988489/