gpt4 book ai didi

c++ - 从子类获取结构并在主类中使用

转载 作者:太空宇宙 更新时间:2023-11-04 12:03:33 27 4
gpt4 key购买 nike

这是我的代码的问题

我有一个父类 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](例如,正方形是 verticlePoint[4],如何将 Point 检索到主类中的变量中,以及然后使用for循环调用shape[0]x,y for verticlePoint[0] to verticlePoint[4 ]

感谢大家的帮助!

最佳答案

显然,您希望根据形状返回不同数量的点。为此,您可以使用例如 std::vector<Point>作为返回类型...例如:

class Shape
{
private:
string name;

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

然后在正方形中,例如,您将返回一个包含 4 个点的 vector ...

std::vector<Point> Square::getVerticlePoint()
{
return std::vector<Point>(verticlePoint, verticlePoint+4);
}

关于c++ - 从子类获取结构并在主类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13101894/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com