0

C++要点笔记(28)——类实例拷贝(copy class)

Posted by nanxiao on 一月 19, 2016 in C++要点笔记 |

(1)赋值运算(=):
先看个例子:

#include <iostream>
using namespace std;

class foo {
public:
    foo& operator=(const foo& other) {cout<<"operator= is called"<<endl;}
};

int main() {
    // your code goes here
    foo a;
    foo b;
    a = b;
    return 0;
}

operator=作用于赋值运算符左面的实例,所以a=b等同于a.operator=(b)。如果你有自定义的析构函数,那么很可能你需要自己实现一个operator=函数。

(2)拷贝构造函数(copy constructor):
定义拷贝构造函数以后,系统就不会产生默认的构造函数了。拷贝构造函数用在下面场景:

Initialize one object from another of the same type.
Copy an object to pass it as an argument to a function.
Copy an object to return it from a function.

看个例子:

#include <iostream>
using namespace std;

class foo {
public:
    //foo& operator=(const foo& other) {cout<<"operator= is called"<<endl;}
    foo(const foo& other) {cout<<"copy constructor is called"<<endl;}
    foo() {}
};

void func1(foo a)
{
}

foo func2()
{
    foo a;
    return a;
}
int main() {
    // your code goes here
    foo a;
    foo b(a);
    func1(a);
    foo c = func2();
    return 0;
}

执行结果如下:

copy constructor is called
copy constructor is called

至于为什么只输出了两次,参考这篇帖子如果你有自定义operator=函数,很可能也需要一个自定义的拷贝构造函数。

 

标签:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Copyright © 2013-2017 我的站点 All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.