类C ++结构 [英] C++ Struct on Class
本文介绍了类C ++结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
需要一些指南
我有一个代码
struct Point
{
int x;
int y;
};
那么在我的班上我有一个函数
class MyClass
{
private:
Point myPoint [4];
public:
void setPoint();
};
void MyClass :: setPoint()
{
int xData,yData;
for(int i = 0; i <4; i ++)
{
cout<< 请输入x-ordinate:;
cin>> xData;
cout<< 请输入y-ordinate:;
cin>> yData;
//在这部分代码引发分段核心转储。
myPoint [i] .x = xData;
myPoint [i] .y = yData;
}
}
在第二循环,分段核心转储发生。
> #includeMyClass.h
int main()
{
MyClass * mClass;
mclass-> setPoint();
}
感谢您的帮助。
解决方案
您必须在使用前分配内存指针:
int main b $ b {
MyClass * mClass = new MyClass();
mclass-> setPoint();
return 0;
}
need some guide here
I got a code which is
struct Point
{
int x;
int y;
};
then at my class i got a function
class MyClass
{
private:
Point myPoint[4];
public:
void setPoint();
};
void MyClass::setPoint()
{
int xData,yData;
for (int i=0;i<4;i++)
{
cout << "Please enter x-ordinate:";
cin >> xData;
cout << "Please enter y-ordinate:";
cin >> yData;
//at this part the code throw a segmentation core dump.
myPoint[i].x = xData;
myPoint[i].y = yData;
}
}
On first run nothing happen, but on 2nd loop, segmentation core dump occur. whats wrong with my code?
Additional code on main.cpp
#include "MyClass.h"
int main()
{
MyClass *mClass;
mclass->setPoint();
}
Thanks for helping.
解决方案
You must allocate memory before use pointer:
int main()
{
MyClass *mClass = new MyClass ();
mclass->setPoint();
return 0;
}
这篇关于类C ++结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文