demo_copy_constructor_b.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 48 行

CPP
48
字号

//***************************************************

# include <iostream.h>
# include <conio.h>

class Sample
{
public:
	Sample() { x=0; y=0; }
	Sample(int i,int j) { x=i; y=j; }
	void copy(Sample &A)  //用对象引用作为函数参数
	{
		if(this==&A)
		{
			cout<<"Can't copy one object to itself!"<<endl;
			return;
		}
		else
			*this=A;
	}
	void add() { x++; y++; }
	void disp()
	{
		cout<<"x="<<x<<", y="<<y<<endl;
	}

private:
	int x,y;
};

void main()
{
	Sample s1(10,20),s2;

	s1.disp();
	s1.add();
	s1.disp();
    getch();
	s2.copy(s2);
    getch();
	s2.copy(s1);
	s2.disp();
	s2.add();
	s2.disp();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?