为了账号安全,请及时绑定邮箱和手机立即绑定

为什么p1,p2这两个对象怎么识别不了?

为什么p1,p2这两个对象怎么识别不了?

C++
宝慕林4294392 2022-12-17 17:13:02
#include<iostream>using namespace std;class point{private:int x;int y;public:point(){}point(int a,int b){x=a;y=b;}int getX(){return x;}int getY(){return y;}};class rect{private:point p1,p2;public:int length,width;void setvalue(){int a1,b1,a2,b2;cout<<"请输入第一个点的数据:x,y:";cin>>a1>>b1;p1=point(a1,b1);cout<<"请输入第二个点的数据:x,y:";cin>>a2>>b2;p2=point(a2,b2);}length=p1.getX()-p2.getX();width=p1.getY()-p2.getY();};int main(){rect rec1;rec1.setvalue();int area;area=length*width;cout<<area;return 0;}创建point类和rect类,rect类有两个point类对象p1,p2私有成员,但是编译时出现错误:'rect::p1' : member from enclosing class is not a type name, static, or enumeratorf:\c++6.0\microsoft visual studio\myprojects\test1\test1.cpp(40) : error C2065: 'p1' : undeclared identifierf:\c++6.0\microsoft visual studio\myprojects\test1\test1.cpp(40) : error C2228: left of '.getX' must have class/struct/union type
查看完整描述

2 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

class rect
{
private:
point p1,p2;
public:
int length,width;
void setvalue()
{
int a1,b1,a2,b2;
cout<<"请输入第一个点的数据:x,y:";
cin>>a1>>b1;
p1=point(a1,b1);
cout<<"请输入第二个点的数据:x,y:";
cin>>a2>>b2;
p2=point(a2,b2);
}
length=p1.getX()-p2.getX(); //这里错了
width=p1.getY()-p2.getY(); //这里错了
// C语言规定,所有代码必须放在函数里面(除了全局变量的声明和初始化)
}; 
---------------------------------------------
建议改为:
//前面的不变
class rect
{
private:
point p1,p2;
public:
int length,width;
void setvalue()
{
int a1,b1,a2,b2;
cout<<"请输入第一个点的数据:x,y:";
cin>>a1>>b1;
p1=point(a1,b1);
cout<<"请输入第二个点的数据:x,y:";
cin>>a2>>b2;
p2=point(a2,b2);
}
int GetLength()
{
length=p1.getX()-p2.getX();
return length;
}
int GetWidth()
{
width=p1.getY()-p2.getY();
return width;
}
};
int main()
{
rect rec1;
rec1.setvalue();
int area;
area=rec1.GetLength()*rec1.GetWidth();
cout<<area;
return 0;
}


查看完整回答
反对 回复 2022-12-21
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

将变量定义为static类型,静态方法访问静态变量。

查看完整回答
反对 回复 2022-12-21
  • 2 回答
  • 0 关注
  • 295 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号