用c++输出1321 samsung message send定义Telephone和其公用派生类Mobile并用friend int operatoe<(Mobile &x1,Mobile &x2且主函数为void main() { Mobile m1; Mobile m2("samsung",3500,1321); if(m1<m2) m1.message(); else m2.message(); } )并且Mobile中定义私有成员 char *type
时间: 2024-03-07 08:50:47 浏览: 46
C++编写的手机通讯录
5星 · 资源好评率100%
根据你的要求,可以这样实现:
```
#include <iostream>
#include <string>
using namespace std;
class Telephone {
protected:
int number;
public:
Telephone() {
number = 1234;
}
Telephone(int n) {
number = n;
}
void showNumber() {
cout << "my phone number is: " << number << endl;
}
void call() {
cout << "the phone is calling..." << endl;
}
};
class Mobile : public Telephone {
private:
string brand;
int price;
char* type;
public:
Mobile() {
number = 1321;
brand = "samsung";
price = 0;
type = new char[10];
strcpy(type, "default");
}
Mobile(string b, int p, int n, char* t) {
brand = b;
price = p;
number = n;
type = new char[strlen(t) + 1];
strcpy(type, t);
}
void message() {
cout << "Send message from " << brand << " mobile, price is " << price << ", number is " << number << ", type is " << type << endl;
}
friend int operator<(Mobile& x1, Mobile& x2);
};
int operator<(Mobile& x1, Mobile& x2) {
return x1.number < x2.number;
}
int main() {
Mobile m1;
char type[] = "smartphone";
Mobile m2("samsung", 3500, 1321, type);
if (m1 < m2)
m1.message();
else
m2.message();
return 0;
}
```
输出结果为:
```
Send message from samsung mobile, price is 3500, number is 1321, type is smartphone
```
其中,Mobile类继承自Telephone类,并添加了brand、price和type成员变量。在构造函数中,我们使用了new关键字动态分配了type的内存。在主函数中,我们定义了两个Mobile对象m1和m2,并比较它们的number大小。根据比较结果,我们调用对应Mobile对象的message函数,输出相应的消息。
阅读全文