如何用C++定义一个类中含两个属性
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何用C++定义一个类中含两个属性相关的知识,希望对你有一定的参考价值。
#include <iostream>using namespace std;
class Person
int age;
bool sex;
public:
Person():age(0),sex(true)
Person(int a, bool s):age(a),sex(s)
Person(const Person &s)age = s.age; sex = s.sex;
~Person()
;
int main()
Person a, b(17, false);
Person c(b);
参考技术A 你说的属性是什么?追问
定义一个Person类,有age(int类型)和sex(bool类型)两个属性。实现其默认构造函数、带参数的构造函数、析构函数和拷贝构造函数.
本回答被提问者采纳中介模式C++实现
中介模式
中介模式是对委托的复杂运用,比如说两个类中,类A中含类B的对象指针作为数据成员,类B中含类A的对象指针作为数据成员。在下面的例子中,中介含有租房者和房东的对象指针,租房者和房东也含有中介的对象指针。完成业务,租房者可以运用其包含的中介对象指针发送给中介包含的房东类的对象的函数成员。房东发送给租房者也一样,具体见代码。
Exe : Mediator.o
g++ -o Exe Mediator.o
main.o : Mediator.cpp
g++ -c -g Mediator.cpp
rm :
Mediator
#include <iostream>
#include <string>
using namespace std;
//中介模式
class Mediator;
class Character
{
public:
Mediator* p_Mediator = NULL;
virtual void set_Meidator(Mediator* p_Mediator) = 0;
virtual void send_msg(string msg) = 0;
virtual void get_msg(string msg) = 0;
};
class Mediator
{
public:
Character* p_ranter = NULL;
Character* p_landlord = NULL;
void set_ranter(Character* p_Character);
void set_landlord(Character* p_Character);
void send_msg(string msg, Character* p_Character);
};
void Mediator::set_ranter(Character* p_Character)
{
this->p_ranter = p_Character;
}
void Mediator::set_landlord(Character* p_Character)
{
this->p_landlord = p_Character;
}
void Mediator::send_msg(string msg, Character* p_Character)
{
if(p_Character == this->p_ranter)
{
this->p_landlord->get_msg(msg);
}
else
{
this->p_ranter->get_msg(msg);
}
}
class Renter : public Character
{
public:
void set_Meidator(Mediator* p_Mediator);
void send_msg(string msg);
void get_msg(string msg);
};
void Renter::set_Meidator(Mediator* p_Mediator)
{
this->p_Mediator = p_Mediator;
}
void Renter::send_msg(string msg)
{
p_Mediator->send_msg(msg, this);
}
void Renter::get_msg(string msg)
{
cout << "Renter get a msg : " << msg << endl;
}
class Landlord : public Character
{
public:
void set_Meidator(Mediator* p_Mediator);
void send_msg(string msg);
void get_msg(string msg);
};
void Landlord::set_Meidator(Mediator* p_Mediator)
{
this->p_Mediator = p_Mediator;
}
void Landlord::send_msg(string msg)
{
p_Mediator->send_msg(msg, this);
}
void Landlord::get_msg(string msg)
{
cout << "Landlord get a msg : " << msg << endl;
}
int main(void)
{
Renter* p_Renter = new Renter;
Landlord* p_Landlord = new Landlord;
Mediator* p_Mediator = new Mediator;
p_Renter->set_Meidator(p_Mediator);
p_Landlord->set_Meidator(p_Mediator);
p_Mediator->set_ranter(p_Renter);
p_Mediator->set_landlord(p_Landlord);
//renter
p_Renter->send_msg("I am a renter , I want a room with 800RMB/M");
p_Landlord->send_msg("I am a landlord, I have a room with 800RMB/M");
delete p_Renter;
delete p_Landlord;
delete p_Mediator;
return 0;
}
以上是关于如何用C++定义一个类中含两个属性的主要内容,如果未能解决你的问题,请参考以下文章