ㅤ穆如春风 2021-07-20 20:29 采纳率: 100%
浏览 29
已采纳

这个为什么报错能帮我找一找错误吗?


#include<iostream>
#include<string>
using namespace std;
class Person
{
    friend ostream& operator<<(ostream& cout, Person p);
public:
    Person(int a);
    ~Person();
    Person& operator=(Person& p)
    {
        if (age != NULL)
        {
            delete(age);
            age = NULL;
        }
        this->age = new int(*p.age);
        return *this;
    }
private:
    int* age;
};
ostream& operator<<(ostream& cout, Person p)
{
    cout << *p.age << endl;
    return cout;
}
Person::Person(int a)
{
    this->age = new int(a);
}
Person::~Person()
{
    if (age != NULL)
    {
        delete(age);
        age = NULL;
    }
}
void test01()
{
    Person a(10);
    Person b(20);
    Person c(30);
    a = b = c;
    cout << a << b << c;
}
int main()
{
    test01();
    return 0;
}
  • 写回答

3条回答 默认 最新

  • CSDN专家-link 2021-07-20 20:35
    关注

    this->age = new int(*p.age);
    由于age是私有变量,所以不能这么访问,必须增加获取age的函数才行
    int getAge() {return age;}
    this->age = new int(p->getAge());

    ostream& operator<<(ostream& cout, Person p)
    {
    cout << *p.age << endl;
    return cout;
    ----这里由于p不是指针对象,所以cout<<p.age就可以了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

问题事件

  • 已采纳回答 7月20日
  • 创建了问题 7月20日

悬赏问题

  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码