说明我的问题我从这里借用代码:Get value from a class member being a pointer
#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 () {
}
class Paper_class{
paper(Rectangle rect);
~paper();
Rectangle * rectangle1;
}
Paper_class::paper(Rectangle rect){
rectangle1 = ▭
}
Paper_class::~paper(){
delete rectangle1;
}
int main () {
vector<Paper_class> vec;
vec.push(Paper_class(new CRectangle(10,10)))
vec.push(Paper_class(new CRectangle(20,20)))
vec.push(Paper_class(new CRectangle(30,30)))
cout << "rect area: " << *vec[1]->rect1.height << endl;
return 0;
}
代码中的这一行不会访问值:
cout << "rect area: " << *vec[1].rect1->height << endl;
如何查看vec [1]中存储的高度? (它应该是20)
提前致谢。
答案 0 :(得分:1)
假设你的意思是:
class Paper_class{
Paper_class(Rectangle rect);
~Paper_class();
Rectangle * rectangle1;
}
Paper_class::Paper_class(Rectangle rect){
rectangle1 = ▭
}
Paper_class::~Paper_class(){
delete rectangle1;
}
使用
cout << "rect area: " << vec[1].rectangle1->height << endl;
vec[1]
评估为Paper_class&
。
vec[1].rectangle1
评估为Rectangle*
。
vec[1].rectangle1->height
评估为double
。
<强>注意强>
由于Paper_Class
中缺少属性复制构造函数和复制赋值运算符,您的代码将导致未定义的行为。有关详细信息,请参阅The Rule of Three。