您的位置:首页 > 移动开发 > Objective-C

函数参数中const 引用 和 传值

2008-09-13 14:14 295 查看
#include <iostream>
using namespace std;

class Object
{
public:
        Object(int i = 1)        { n = i;    cout << "Object::Object()" << endl; }
        Object(const Object& a)    
        {
            n = a.n;    
            cout << "Object::Object(const Object&)" << endl;
        }
        ~Object()                { cout << "Object::~Object()" << endl; }

        void inc()                { ++n; }
        int val() const            { return n; }

private:
        int n;
};

void foo(Object a)
{
        cout << "enter foo, before inc(): inner a = " << a.val() << endl;
        //a.inc();
        cout << "enter foo, after inc(): inner a = " << a.val() << endl;
}

int main()
{
        Object a;       
    
        cout << "before call foo : outer a = " << a.val() << endl;
        foo(a);         
        cout << "after call foo : outer a = " << a.val() << endl;      
    
        return 0;
}

可以进行测试便得知,传引用只需要调用构造函数一次,而传值需要2次。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  object include 测试