void show(inta,int b)与void show(int x,int y)构成方法重载吗
时间: 2023-12-13 13:03:01 浏览: 47
是的,`void show(int a, int b)` 和 `void show(int x, int y)` 构成方法重载。方法重载指的是在同一个类中定义多个具有相同名称但参数列表不同的方法。在这种情况下,方法名称相同,但参数列表中的参数名称和类型不同。
在你提供的例子中,`show` 方法的名称相同,但参数列表中的参数名称和类型不同:一个方法有 `int a` 和 `int b` 作为参数,另一个方法有 `int x` 和 `int y` 作为参数。这符合方法重载的定义。
通过方法重载,你可以根据不同的参数类型和个数来调用不同的方法,提高代码的灵活性和复用性。在使用时,编译器会根据调用时提供的参数类型和个数来确定具体调用哪个重载方法。
相关问题
定义一个类three_d如下: class three_d { public: three_d(int x=0,int y = 0,int z = 0); void show(); private: int a,b,c; }; 重载“+”,以便实现运算符可以进行下面的计算: ob+int; Int+ob; 其中ob为three_d类对象。
可以通过以下方式来重载运算符"+":
```c++
three_d operator+(const three_d& ob, int num) {
return three_d(ob.a + num, ob.b + num, ob.c + num);
}
three_d operator+(int num, const three_d& ob) {
return three_d(num + ob.a, num + ob.b, num + ob.c);
}
```
这里重载了两个"+"运算符,一个用于three_d对象加上一个整数,另一个用于整数加上一个three_d对象。在这两个运算符中,都创建了一个新的three_d对象,其三个成员变量的值分别是原来的对象和整数之间的和。
设计一个点类Point,实现点对象之间的+和-运算。 #include<iostream> using namespace std; 提供补充代码 int main() { Point p1,p2,psum,psub; int x,y; cin>>x>>y; p1.setP(x,y); cin>>x>>y; p2.setP(x,y); psum=p1+p2; psub=p1-p2; cout<<"两点相加:"; psum.show(); cout<<"两点相减:"; psub.show(); }
以下是实现点类Point的代码:
```c++
#include<iostream>
using namespace std;
class Point{
private:
int x, y;
public:
void setP(int a, int b){
x = a;
y = b;
}
void show(){
cout << "(" << x << "," << y << ")" << endl;
}
Point operator+(const Point &p){
Point tmp;
tmp.x = x + p.x;
tmp.y = y + p.y;
return tmp;
}
Point operator-(const Point &p){
Point tmp;
tmp.x = x - p.x;
tmp.y = y - p.y;
return tmp;
}
};
int main() {
Point p1, p2, psum, psub;
int x, y;
cin >> x >> y;
p1.setP(x, y);
cin >> x >> y;
p2.setP(x, y);
psum = p1 + p2;
psub = p1 - p2;
cout << "两点相加:";
psum.show();
cout << "两点相减:";
psub.show();
return 0;
}
```
在Point类中,重载了运算符+和-,实现了点对象之间的加法和减法运算。在主函数中,首先创建了两个点对象p1和p2,并通过setP方法设置了它们的坐标。然后通过重载的运算符+和-,计算出了两点之间的加法和减法,并将结果保存在psum和psub对象中。最后,通过show方法输出了两点相加和相减的结果。