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

Woj*_*zyk 1 c++ pointers

给出以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能让最后的cout陈述起作用?

Mar*_*ins 6

移动解除引用运算符. p->height指整数指针height.然后把*前面的那个取消引用int指针.

cout << "rect area: " << *p->height << endl;
Run Code Online (Sandbox Code Playgroud)