C ++组合程序错误(xcor未声明)

时间:2012-04-10 16:24:52

标签: c++

错误!xcor在setAll()函数

未声明

我在Circle类中创建了PointType对象来进行组合排序,但是在Circle的构造函数初始化时它显示了

“[错误]'ycor'未在此范围内声明”

“[错误]'xcor'未在此范围内声明”

我想在我的Circle类中使用xcor和ycor,以便使用setAll()函数获取Radius

请帮忙!我搞砸了。

#include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;

class PointType{

    private:

    int xcor;//x coordinate
    int ycor;//y coordinate
    public:

    PointType();//constructor
    PointType(int x,int y);
    void setPoint(int x,int y);
    int getx() const;
    int gety() const;


};  
PointType::PointType():xcor(0),ycor(0)
{

}   

PointType::PointType(int x,int y):xcor(x),ycor(y){
}

void PointType::setPoint(int x,int y){
    xcor=x;
    ycor=y;

}

int PointType::getx() const{
    return xcor;
    }


int PointType::gety() const{
    return ycor;
    }

class Circle{

    protected:
        float Radius;
        float Area;
        int Circumference;
        float pi;
        PointType obj1;

    public:

    Circle();
    void setAll();
    float getRadius();

    float getArea();


    float getCircumference();
    void callFunction();
    void printAll();
    void pt(int x,int y);


};  

Circle::Circle():Radius(0),Area(0),Circumference(0),pi(3.1415),obj1(xcor,ycor){
}

void Circle::setAll(){

        Radius=sqrt(  (xcor*xcor)  + (ycor*ycor)  );
        Area=pi*Radius*Radius;
        Circumference=2*pi*Radius;
}

float Circle::getRadius(){
    return Radius;
}

float Circle::getArea(){
    return Area;
}

float Circle::getCircumference(){
    return Circumference;
}

void Circle::printAll(){

        cout<<"The Area is :"<<Area<<endl;
        cout<<"The Circumference is :"<<Circumference<<endl;    
    }
void Circle::pt(int x,int y){
    obj1.setPoint(x,y);

}

3 个答案:

答案 0 :(得分:0)

您的班级Circle没有任何名为xcorycor的成员变量。如果您想获取PointType对象的值,则setAll函数应如下所示:

Radius=sqrt(  (obj1.getx()*obj1.getx())  + (obj1.gety()*obj1.gety())  );

此外,您还必须更改构造函数:

Circle::Circle():Radius(0),Area(0),Circumference(0),pi(3.1415),obj1(0,0)

因为它无法访问任何xcorycor

答案 1 :(得分:0)

声明xcor,ycor为Circle'构造函数参数,

在计算Radius:

之前添加此行
int xcor = obj1.getx(), ycor = obj1.gety();
Radius=sqrt(  (xcor*xcor)  + (ycor*ycor)  );

您还可以考虑继承Circle的PointType,而不是嵌入的obj1:

class Circle : public PointType
{
public: Circle(int x, int y):PointType(x, y) {}
...
/* remove obj1 */
}

答案 2 :(得分:0)

  1. 你必须改变你的Circle构造函数,因为它对xcor和ycor一无所知:

    Circle::Circle():Radius(0),Area(0),Circumference(0),pi(3.1415),obj1(42,56)

  2. Circle类仍然不知道xcor和ycor,所以你必须改变setAll方法:

    Radius=sqrt( static_cast<double>((obj1.getx()*obj1.getx()) + (obj1.gety()*obj1.gety())) );