如何在C++中使用复合继承?
我对如何将组合与继承结合使用感到困惑。根据我的理解,我写了一个简单的例子。请帮帮我。 1上述代码是否正确? 2我的多重继承实现正确吗? 我在员工课上做继承和写作。对吗如何在C++中使用复合继承?,c++,C++,我对如何将组合与继承结合使用感到困惑。根据我的理解,我写了一个简单的例子。请帮帮我。 1上述代码是否正确? 2我的多重继承实现正确吗? 我在员工课上做继承和写作。对吗 class address { private: public: struct MyStruct { int houseno; string colony; string city; }; MyStruct m; //shows
class address
{
private:
public:
struct MyStruct
{
int houseno;
string colony;
string city;
};
MyStruct m;
//shows the address
void get_address()
{
cout << m.houseno;
cout<<m.colony;
cout << m.city;
}
};
class telephoneNo
{
private:
string c;
public:
// takes the telephoneNo of the employee from user and pass to local variable
void set_telephone(string d)
{
c = d;
}
void get_telephone()
{
cout << c;
}
};
//multiple level inheritance
class employee :public address, public telephoneNo
{
private:
string name;
public:
address obj; //composition
telephoneNo obj2; // composition
void employee_name(string a)
{
name = a;
}
void show_emplyeeDetail()
{
cout << "Employee's Name is: ";
cout << name<<endl;
cout << "Employee's Address is: ";
obj.get_address();
cout<<endl;
cout << "Employee's Telephnoe no is: ";
obj2.get_telephone();
cout<< endl;
}
};
void main()
{
emp.obj;
cout << "Enter Name of employee " << endl;
cin >> nameInput;
cout << "-----------Enter address of employee----------- "<<endl;
cout << "Enter house: ";
cin >> emp.obj.m.houseno; //passing parameters to the struct
cout << "Enter colony : ";
cin >> emp.obj.m.colony;
cout << "Enter city: ";
cin >> emp.obj.m.city;
cout << "Enter telephone of employee: ";
cin >> telephoneInput;
emp.employee_name(nameInput);
emp.obj2.set_telephone(telephoneInput);
cout << "-------------Employee's Details are as follows------------ " << endl;
emp.show_emplyeeDetail();
}
您的员工是一个地址和一个电话号码——这是多重继承
class employee :public address, public telephoneNo
基本上,您可以为任何员工访问这两个基类的公共字段和方法,例如
employee employee1;
employee1.get_address();
另一方面,员工有一个地址和电话号码——这就是构成
employee1.obj.get_address();
请注意,您员工的两个地址和电话号码严格分开,可能包含不同的内容
最好的建议是从一本关于C++的初学者的入门书开始。你有问题吗?你需要读一个类地址{私立:公共:一个全新的冗长级别。{是的,我知道我可以使用struct作为地址,但为了实现多重继承,我把它做成了一个类……这是一种正确的继承组合实现方法吗??