C++任意创建一个类,要求包含构造函数,类的对象,析构函数,友元函数,并进行测试

2024-12-05 08:40:36
推荐回答(4个)
回答1:

/*#include
using namespace std;

class Clock;//类的声明

class RepairMan
{
public:
bool RepairClock(Clock& clock);
//...
RepairMan();
~RepairMan();
};

class Clock
{
public:
//friend class RepairMan;
friend bool RepairMan::RepairClock(Clock& clock);
Clock(int hour = 0, int minute = 0);
~Clock();
void ShowTime();
private:
void ReSetWheelA() { m_hour = 0; m_WheelAState = true; }
void ReSetWheelB() { m_minute = 0; m_WheelBState = true; }
bool m_WheelAState; //监控m_hour的状态
bool m_WheelBState; //监控m_minute的状态
int m_hour;
int m_minute;
const string m_serial_number;

};

Clock::Clock(int hour, int minute)
:m_hour(hour), m_minute(minute), m_serial_number("123-456"), m_WheelAState(true), m_WheelBState(true)
{
if (m_hour>=24 || m_hour<0)
{
m_WheelAState = false;
cout<<"小时范围出错!";
}
if (m_minute>=60 || m_minute<0)
{
m_WheelBState = false;
cout<<"分钟范围出错!";
}
}//同样的SetTime函数也可以做同样的修改

bool RepairMan::RepairClock(Clock& clock){
bool bIsRepaired = false;
if (!clock.m_WheelAState)
{
clock.ReSetWheelA();
bIsRepaired = true;
}
if (!clock.m_WheelBState)
{
clock.ReSetWheelB();
bIsRepaired = true;
}
return bIsRepaired;
}

int main()
{
return 0;
}*/
//方法三:
#include
using namespace std;

class Clock
{
public:
friend class RepairMan;
friend bool RepairClock(Clock& clock);
Clock(int hour = 0, int minute = 0);
~Clock();
void ShowTime();
private:
void ReSetWheelA() { m_hour = 0; m_WheelAState = true; }
void ReSetWheelB() { m_minute = 0; m_WheelBState = true; }
bool m_WheelAState; //监控m_hour的状态
bool m_WheelBState; //监控m_minute的状态
int m_hour;
int m_minute;
const string m_serial_number;

};

Clock::Clock(int hour, int minute)
:m_hour(hour), m_minute(minute), m_serial_number("123-456"), m_WheelAState(true), m_WheelBState(true)
{
if (m_hour>=24 || m_hour<0)
{
m_WheelAState = false;
cout<<"小时范围出错!";
}
if (m_minute>=60 || m_minute<0)
{
m_WheelBState = false;
cout<<"分钟范围出错!";
}
}//同样的SetTime函数也可以做同样的修改

bool
RepairClock(Clock& clock){
bool bIsRepaired = false;
if (!clock.m_WheelAState)
{
clock.ReSetWheelA();
bIsRepaired = true;
}
if (!clock.m_WheelBState)
{
clock.ReSetWheelB();
bIsRepaired = true;
}
return bIsRepaired;
}

class RepairMan
{
public:
bool RepairClock(Clock& clock);
//...
RepairMan();
virtual ~RepairMan();
};
bool RepairMan::RepairClock(Clock& clock){
bool bIsRepaired = false;
if (!clock.m_WheelAState)
{
clock.ReSetWheelA();
bIsRepaired = true;
}
if (!clock.m_WheelBState)
{
clock.ReSetWheelB();
bIsRepaired = true;
}
return bIsRepaired;
}

回答2:

#include
using namespace std;

class User{
public:
User(char* u_name,int u_age)//构造
{
name = new char[strlen(u_name)+1];
strcpy(name,u_name);
age = u_age;
}
~User()//析构
{
delete[] name;
}

private:
char* name;
int age;
friend ostream& operator<<(ostream&os,User&user);

};
ostream& operator<<(ostream&os,User&user)//友元
{
return os<<"name:"<}

int main()
{
User user("David",19);
cout<}

回答3:

?

回答4:

倒数4分