C++普通构造函数、拷贝构造函数(对象不含指针成员)、赋值运算符重载函数最简单实例

    技术2022-07-15  68

    在Student类中演示这三种构造函数

    #include <QCoreApplication> #include "iostream" using namespace std; class Student{ private: string name; int age; public: //缺省构造函数 Student(){ } //有参构造函数 Student(string _name, int _age){ name = _name; age = _age; } //拷贝构造函数 Student(const Student& _s){ name = _s.name; age = _s.age; } //赋值运算符重载函数 Student& operator = (const Student& _s){ //防止自我赋值 if (this == &_s){ return *this; } this->name = _s.name; this->age = _s.age; return *this; } //析构函数 ~Student(){ } string getName(){ return name; } int getAge(){ return age; } void setName(string _name){ name = _name; } void setAge(int _age){ age = _age; } }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); /**************************************Test START****************************************/ Student s; //缺省构造 s.setName("loupeihuang"); s.setAge(3); cout<<s.getName()<<" "<<s.getAge()<<endl; Student s1("suntian",6); //有参构造 cout<<s1.getName()<<" "<<s1.getAge()<<endl; Student s2(s1); //拷贝构造 cout<<s2.getName()<<" "<<s2.getAge()<<endl; //此操作其实是分两步进行的 //第一步:调用运算符重载函数,返回一个临时的Student对象 //第二步:调用拷贝构造函数,将临时对象拷贝给对象s2 Student s3 = s1; //运算符重载+拷贝构造 cout<<s3.getName()<<" "<<s3.getAge()<<endl; /**************************************Test END****************************************/ return app.exec(); }

    运行结果

    Processed: 0.012, SQL: 9