C++ 学习之路(3):向函数传递对象

来源:互联网 发布:自学英语口语的软件 编辑:程序博客网 时间:2024/05/22 13:47
// 向函数传递对象#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;}
0 0