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

时间:2011-11-02 23:15:41

标签: 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;
}

如何才能使上一个cout语句生效?

2 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:0)

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