C++学習の道(3):関数にオブジェクトを渡す
3302 ワード
//
#include <iostream>
using namespace std;
class aClass
{
public:
aClass(int n)
{ i = n; }
void set(int n)
{ i = n; }
int get()
{ return i; }
private:
int i;
};
// ( )
void sqr1(aClass ob)
{
ob.set(ob.get()*ob.get());
cout<<"Copy of obj has i value of ";
cout<<ob.get()<<endl;
}
// ( )
void sqr2(aClass *ob)
{
ob->set(ob->get()*ob->get());
cout<<"Copy of obj has i value of ";
cout<<ob->get()<<endl;
}
//
void sqr3(aClass &ob)
{
ob.set(ob.get()*ob.get());
cout<<"Copy of obj has i value of ";
cout<<ob.get()<<endl;
}
int main()
{
aClass obj(10);
cout<<"---- ----"<<endl;
sqr1(obj);
cout<<"But, obj.i is unchanged in main:";
cout<<obj.get()<<endl;
cout<<"---- ----"<<endl;
sqr2(&obj);
cout<<"Now, obj.i in main() has been changed. :";
cout<<obj.get()<<endl;
cout<<"---- ----"<<endl;
// obj i , 。
obj.set(10);
sqr3(obj);
cout<<"Now, obj.i in main() has been changed. :";
cout<<obj.get()<<endl;
return 0;
}