C++的友元素问题
本帖最后由 M_bells 于 2021-5-20 17:45 编辑封闭类的成员函数试图直接访问内部类的私有成员,结果不成功
不能访问Date类的三个私有成员:year、month、day
#include <iostream>
using namespace std;
class Date;
class Date //日期类
{
private:
int year;
int month;
int day;
public:
Date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
void set_date(int y, int m, int d)
{
year = y;
month = m;
day = d;
}
void print()
{
cout << year << "年" << month << "月" << day << "日" << endl;
}
};
class Person //个人类
{
private:
long ID; //编号
Date birthday; //出生日期
public:
Person(long id, int by, int bm, int bd) :birthday(by, bm, bd)
{
ID = id;
}
void display()
{
cout << "编号: " << ID << endl;
cout << "出生日期: ";
birthday.print();
}
void set_birthday(int y, int m, int d)//希望直接修改出生日期的数据
{
birthday.year = y; //这里错误!!
birthday.month = m;
birthday.day = d;
}
};
int main()
{
Person p1(123456L, 1980, 12, 3);
p1.display();
p1.set_birthday(1990, 12, 3);
return 0;
}
请问一下怎么修改能访问Date的数据 需要在Date里声明友元类friendclassPerson;这样Person类才能访问Date类的私有变量
页:
[1]