delete cpp 2019-05-06 03:55 采纳率: 50%
浏览 373
已采纳

加号运算符重载中匿名对象以及拷贝构造函数和加号运算符重载的问题?

**1.下列程序运行中,stu0103和stu0104的地址和stu0102、stu0101的地址相差比较大。请问为什么,分别存在什么区?
2.请问加号运算符重载中是否调用了拷贝构造函数?
**

#include<iostream>
#include<string>
using namespace std;

class Student_t {

public:
    Student_t():Student_t("Lilei",18) {}
    Student_t(const std::string name,const int age,const int high = 175) :name(name), age(age), high(high) {
**      //学生人数++**
        number_of_stu++;
    }

    //成员加号运算符重载
    Student_t operator+(Student_t& stu);

private:
    std::string name;//学生姓名
    int age;//年龄
    int high;//身高
    static int number_of_stu;//学生人数
};

extern std::ostream& operator<<(std::ostream& os, const 
Student_t& stu);

//成员加号运算符重载
Student_t Student_t::operator+(Student_t& stu) {
    return Student_t(this->name + stu.name, this->age + stu.age,this->high + stu.high);
}

int main()
{
    //堆空间对象
    Student_t* stu0101 = new Student_t("C",10);
    Student_t* stu0102 = new Student_t("X",9);

    Student_t* stu0103 = &(*stu0101 + *stu0102);
    cout << *stu0103 << endl;

    Student_t* stu0104 = &(*stu0101 + *stu0103);
    cout << *stu0104 << endl;

    cout << stu0101 << " " << stu0102 << " " << stu0103 << " "<< stu0104<<endl;

    system("pause");
    return 0;
}

展开全部

  • 写回答

1条回答 默认 最新

  • 「已注销」 2019-05-06 05:26
    关注

    stu0101 stu0102 存在堆区,这两个变量的地址相差不大。
    stu0103 stu0104 存在栈区,这两个变量的地址相差不大。
    像这种临时的即将销毁的变量,属于右值变量,可以在函数中进行对这个变量进行取地址,或者说是通过const来延长生命周期
    然后获取地址。

    你这里加号并没有进行拷贝构造。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部