计划不如变化、学 C++

C++中的传递引用 与 返回引用:

#include <iostream>
#include "Point.cpp"


Point &F(Point &p);

int main()
{
Point p(3, 5);

std::cout << "X: " << p.GetX() << " Y: " << p.GetY() << std::endl;

p.AddX();
p.AddY();

std::cout << "X: " << p.GetX() << " Y: " << p.GetY() << std::endl;


Point &p2 = F(p);

std::cout << "X: " << p.GetX() << " Y: " << p.GetY() << std::endl;

std::cout << "p2.X: " << p2.GetX() << " p2.Y: " << p2.GetY() << std::endl;

p2.AddX();
p2.AddY();

std::cout << "X: " << p.GetX() << " Y: " << p.GetY() << std::endl;

int x;
std::cin>> x;

return 0;
}

Point &F(Point &p)
{
p.AddX();
p.AddY();
return p;
}




Point.cpp 

#include <iostream>

class Point
{
private :
int mX, mY;


public:

Point(int x,int y)
{
mX = x;
mY = y;
}

int GetX()
{
return mX;
}

int GetY()
{
return mY;
}

void AddX()
{
mX++;
}
void AddY()
{
mY++;
}

};

运行结果:

计划不如变化、学 C++_第1张图片

 

你可能感兴趣的:(C++)