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

在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();
}

运行结果

在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值