1

ここに私のコードの問題があります

親クラスShapeと子クラスがありますSquare

struct Point
{
    int x,y;
};

class Shape
{
private:
    string name;

public:
    void setName(string);
    string getName();
    virtual void setVerticlePoint() { };
    virtual Point getVerticlePoint();
};

以下はSquare.cppです

class Square: public Shape
{
private:
    Point verticlePoint[4];

public:
    int noOfVerticles() const { return 5; }
    void setVerticlePoint();
    Point getVerticlePoint();
};

void Square::setVerticlePoint()
{
    int xData,yData;

    for(int i=0; i<4; i++)
    {
        cout << "Please enter x-ordinate of pt." << i << " :";
        cin > xData;
        cout << "Please enter y-ordinate of pt." << i << " :";
        cin >> yData;
        verticlePoint[i]->x = xData;
        verticlePoint[i]->y = yData;
    }
}

だから main.cpp で、私はこれをやった

int main()
{
    Shape *point[5];
    Point vertic`lePoint;
    Square *cro = new Square();

    // some codes in between

    // now i prompt for verticle point

    shape[0] = squr;

    //assuming myShape & myType is some string value
    shape[0]->setName(myShape);
    shape[0].setType(myType);

    //here i will be prompt to key in 4 times of X & y Ordinate of the verticle point
    shape[0]->setVerticlePoint();

    //Now the issue is i need to retrieve back my verticle point that i store in shape[0].

    //here no issue
    cout << "Get Name: " << shape[0]->getName() << endl;
    cout << "Get Data:"  << shape[0]->getType() << endl;
    //the top 2 works

    //this is the issue
    verticlePoint = shape[0]->getVerticlePoint();
    cout << sizeof(verticlePoint);
    //it output as size 8 , no matter which shape i use, i got other shapes with different verticle point.

    return 0;
}

問題は次のとおりです。

を取得する方法verticlePoint[array](例: for square is verticlePoint[4]、Point を取得してメイン クラスの変数に格納し、for ループを使用してx,yof のshape[0]forverticlePoint[0]を呼び出す方法)verticlePoint[4]

助けてくれてありがとう!

4

1 に答える 1

1

どうやら、形状に応じて異なる数のポイントを返したいようです。これを行うには、たとえばstd::vector<Point>戻り値の型として使用できます...たとえば:

class Shape
{
private:
    string name;

public:
    void setName(string);
    string getName();
    virtual void setVerticlePoint() { };
    virtual std::vector<Point> getVerticlePoint();
};

たとえば、正方形では、4点のベクトルを返します...

std::vector<Point> Square::getVerticlePoint()
{
    return std::vector<Point>(verticlePoint, verticlePoint+4);
}
于 2012-10-27T16:26:56.673 に答える