起因是本人想要在一个类中的函数通过指针调用另一个类的私有数据成员,但发现,修改前代码一与代码二输出结果不同,但经过修改过后,偶然发现,修改后代码一与代码二输出结果相同,百思不得其解,故发出疑问。
代码一(修改前)
static double calArea( const Rectangle&p2)
{
const Rectangle* p1 = &p2;
double Height = ((double)p1);
p1++;
double Width = ((double)p1);
return Height * Width;
}
代码一(修改后)
static double calArea( const Rectangle&p2)
{
const Rectangle* p1 = &p2;
double Height = ((double)p1);
p1++;
double Width = ((double)p1-1);
return Height * Width;
}
代码二:
static double calArea( const Rectangle&p2)
{
const Rectangle* p1 = &p2;
double Height = ((double)p1+0);
double Width = ((double)p1+1);
return Height * Width;
}
被调用类的那部分代码:
class Rectangle{
double height,width;
public:
Rectangle(double h,double w):height(h),width(w){}
double getHeight()const{
return height;
}
double getWidth()const{
return width;
}
};