从儿童课程中获得结构,并在主班上使用
Get Struct from child class and use in main class
这是我的代码
的问题我有一个父级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]
,如何将点检索到主类中的变量中,然后使用for loop来调用verticlePoint[0]
的x,y
,for CC_7 for 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分...
的向量std::vector<Point> Square::getVerticlePoint()
{
return std::vector<Point>(verticlePoint, verticlePoint+4);
}
相关文章:
- 如何在C++中使用结构生成映射
- 在基于范围的for循环中使用结构化绑定声明
- 访问存储在向量C++中的结构的多态成员
- JSON转换为nlohmann JSON-lib中的结构数组
- 访问类lintalizer列表中的结构元素
- C++:映射结构中的结构指针
- 在另一个线程中调用luaL_error会引发qWarning
- C++在不同线程中改变向量
- 从字符串中获取结构的大小
- 使用cpp中的结构和函数的多个学生条目
- C++线程中,没有重载函数接受 X 参数
- 如何在 c++ 中创建结构向量的映射
- 调用 C 文件中的"C++"结构
- 如何从线程中的不同模块调用函数?
- 使用结构成员指针在C++中填充结构
- 在std::线程中使用已分配的结构数据
- 从线程执行的函数中返回结构数组
- OpenMP中树结构的线程安全性
- 当结构数组在主线程中填充数据时,从结构数组的低索引元素读取是否线程安全
- 多线程插件体系结构中的共享、单侧可变状态