copy构造函数调用情况

很早知道拷贝构造函数被调用有三种情况:

1)类对象初始化该类的另一对象时;

2)形参为类对象的函数被调用时;

3)返回值为类对象的函数执行完成返回调用者时。

但今天才发现理解的和实际情况有偏差,并不是出现赋值运算符=就是调用的赋值操作运算符函数啊,比如这里的1),类对象初始化另一对象时是可以用拷贝构造函数形式,也可以利用赋值符号的形式啊,类似内置类型的初始化,用一个简单的类来验证了该事实。

#include <iostream>
#include <string>

using namespace std;


int main()
{
    class Foo{
    public:
        Foo()
        {
            myFun("This is from default constructor--Build-in type is not initialized!");
        }
        Foo(const Foo& rhs)
        {
            this->a = rhs.a+1;
            this->s = rhs.s;
            myFun("This is from copy constructor");
        }
        Foo& operator=(const Foo& rhs)
        {
            this->a = rhs.a+2;
            this->s = rhs.s;
            myFun("This is from  =operator");
            return *this;
        }
        Foo(int aa, string ss):a(aa),s(ss)
        {
            myFun("This is from constructor with Constructor Initializer List");
        }
        ~Foo(){}
        void myFun(string str)
        {
            cout << a << ends << s << endl << str << endl;
        }
    private:
        int a;
        string s;


    };
    Foo foo(3,"good");
    Foo foo1;//初始化
    Foo foo2=foo;
    Foo foo3(foo);


    foo1=foo;//这才是赋值
    return 0;
}
运行结果:

从结果可以看出只有最后一句才是来自赋值运算符,其上两个来自拷贝构造函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值