C++ 复制构造函数与return

cpp-copy-constructor.jpg
为了研究方便,定义 student类:

class Student {
public:
    int num;
    //构造函数
    Student(int num = 0) {
        this -> num = num;
        std::cout << "调用构造函数! num=" << num << std::endl;
    }
    
    //析构函数
    ~Student() {
        std::cout << "调用析构函数! num=" << num << std::endl;
    }
    
    //复制构造函数
    Student(const Student &stu) {
        num = stu.num;
        std::cout << "调用复制构造函数! num=" << num << std::endl;
    }
};

赋值

// int main(int argc, char** argv)
    Student s1(1);
    Student s2(2);
    s1 = s2;
    s2.num = 233;
    std::cout << s1.num << std::end;

输出

调用构造函数! num=1
调用构造函数! num=2
2

说明第四行赋值语句仅将s2值逐位赋给s1,并不会创建新的对象。

函数返回值

// func
Student createStudent() {
    Student student;
    return student;
}
// int main(int argc, char** argv)
Student student = createStudent();

输出

调用构造函数! num=0
调用复制构造函数! num=0
调用析构函数! num=0

说明函数返回对象时需要复制对象,并将函数执行过程中的临时对象回收。

完整程序

#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
class Student {
public:
    int num;
    //构造函数
    Student(int num = 0) {
        this->num = num;
        std::cout << "调用构造函数! num=" << num << std::endl;
    }

    //析构函数
    ~Student() {
        std::cout << "调用析构函数! num=" << num << std::endl;
    }

    //复制构造函数
    Student(const Student& stu) {
        num = stu.num;
        std::cout << "调用复制构造函数! num=" << num << std::endl;
    }
};

Student createStudent() {
    Student student;
    return student;
}

int main(int argc, char** argv) {
    Student s1(1);
    Student s2(2);
    s1 = s2;
    s2.num = 233;
    std::cout << s2.num << std::endl;
    std::cout << "\n\n" << std::endl;
    system("pause");
    Student s0 = createStudent();
    std::cout << "\n\n" << std::endl;
    system("pause");
    return 0;
}
最后修改:2020 年 07 月 01 日
如果觉得我的文章对你有用,请随意赞赏