最赞回答 / xhuanhero
你说的应该是在构造函数里面初始化成员变量构造函数:Coordinate(int x, int y):m_iX(x),m_iY(y){};注意这个构造函数是必须带参数的,要不然无法初始化成员变量
2018-01-28
struct Coordinate {
public:
Coordinate(int x, int y):m_iX(x),m_iY(y) {
cout << "(" << x << "," << y << ")" << endl;
}
int m_iX;
int m_iY;
};
int main(void){
Coordinate *site1 = new Coordinate(3, 5);
delete site1;
}
public:
Coordinate(int x, int y):m_iX(x),m_iY(y) {
cout << "(" << x << "," << y << ")" << endl;
}
int m_iX;
int m_iY;
};
int main(void){
Coordinate *site1 = new Coordinate(3, 5);
delete site1;
}
成了
Coordinate(int x,int y)
{
m_iX = x;
m_iY = y;
}
void printInfo()
{
cout<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
public:
int m_iX;
int m_iY;
};
int main(void)
{
Coordinate coorArr[2] = {{1,2},{3,4}};
for(int i = 0; i < 2; i++)
{
coorArr[i].printInfo();
}
Coordinate(int x,int y)
{
m_iX = x;
m_iY = y;
}
void printInfo()
{
cout<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
public:
int m_iX;
int m_iY;
};
int main(void)
{
Coordinate coorArr[2] = {{1,2},{3,4}};
for(int i = 0; i < 2; i++)
{
coorArr[i].printInfo();
}
加了个成员函数才过,构造函数改不好
...
void getXY(int x,int y)
{
m_iX = x;
m_iY = y;
}
void printInfo()
{
cout<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
public:
int m_iX;
int m_iY;
};
int main(void)
{
Coordinate coorArr[2];
coorArr[0].getXY(1,2);
coorArr[1].getXY(3,4);
...
...
void getXY(int x,int y)
{
m_iX = x;
m_iY = y;
}
void printInfo()
{
cout<<"("<<m_iX<<","<<m_iY<<")"<<endl;
}
public:
int m_iX;
int m_iY;
};
int main(void)
{
Coordinate coorArr[2];
coorArr[0].getXY(1,2);
coorArr[1].getXY(3,4);
...