用c++输出1321 samsung message send定义Telephone和其公用派生类Mobile并用friend int operatoe<(Mobile &x1,Mobile &x2)
时间: 2024-03-07 12:50:45 浏览: 166
可以这样实现:
```
#include <iostream>
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 {
public:
Mobile() {
number = 1321;
}
Mobile(int n) {
number = n;
}
friend int operator<(Mobile& x1, Mobile& x2);
};
int operator<(Mobile& x1, Mobile& x2) {
return x1.number < x2.number;
}
int main() {
Mobile m1, m2(2000);
cout << m1.number << endl;
cout << m2.number << endl;
cout << (m1 < m2) << endl;
return 0;
}
```
输出结果为:
```
1321
2000
1
```
其中,Mobile类继承自Telephone类,重载了小于运算符,并且将其声明为了`friend`函数,可以直接访问Mobile类的成员变量。在`main`函数中,我们定义了两个Mobile对象m1和m2,并输出它们的number。最后,我们比较了m1和m2的number大小,并输出结果。
阅读全文