#include<iostream> using namespace std; class Vehicle { protected: int speed; int wheel; public: Vehicle(){} virtual void Display() = 0; }; class Bicycle :virtual public Vehicle { public: Bicycle(int s, int w) { s = speed, w = wheel; } void Display() { cout << "Bicycle:" << speed << "," << wheel << endl; } }; class Car :virtual public Vehicle { public: Car(int s, int w) { s = speed, w = wheel; } void Display() { cout << "Car:" << speed << "," << wheel << endl; } }; class Motocycle :public Bicycle, public Car { public: Motocycle(int s, int w):Bicycle(s,w),Car(s,w){} void Display() { cout << "Motocycle:" << speed << "," << wheel << endl; } }; int main() { Bicycle b(20, 2); b.Display(); Car c(40, 4); c.Display(); Motocycle m(30, 2); m.Display(); return 0; }运行结果为什么不对
时间: 2024-03-24 08:35:58 浏览: 65
程序的运行结果不对是因为在 Bicycle 和 Car 类的构造函数中,将传入的参数赋值给了成员变量时,出现了错误。正确的做法应该是将成员变量和传入的参数名字进行区分,如下所示:
```
class Bicycle :virtual public Vehicle {
public:
Bicycle(int s, int w) { speed = s, wheel = w; }
void Display() { cout << "Bicycle:" << speed << "," << wheel << endl; }
};
class Car :virtual public Vehicle {
public:
Car(int s, int w) { speed = s, wheel = w; }
void Display() { cout << "Car:" << speed << "," << wheel << endl; }
};
```
在 Motocycle 类的构造函数中也需要对 Bicycle 和 Car 的构造函数进行调用,正确的写法如下:
```
Motocycle(int s, int w):Bicycle(s,w),Car(s,w),Vehicle(){}
```
修改后的程序运行结果如下:
```
Bicycle:20,2
Car:40,4
Motocycle:30,2
```
相关问题
#include <iostream> using namespace std;
#include <iostream> 是C++编程语言中的预处理指令,用于包含标准输入输出流库(Input/Output Stream Library),也就是常说的iostream。iostream库包含了基本的输入输出操作函数,如cin(用于从标准输入读取数据)、cout(用于向标准输出(通常是屏幕)输出数据)等。
`using namespace std;` 是C++中的命名空间声明,std是标准命名空间,用来避免在程序中频繁写出std::这样的前缀。当你使用`using namespace std;`后,就可以直接使用iostream库中的成员函数,例如cout、cin、endl等,而无需每次都加上std::前缀。
以下是这两句代码的作用示例:
```cpp
// 包含iostream库
#include <iostream>
// 使用std命名空间中的函数
using namespace std;
int main() {
cout << "Hello, World!" << endl; // 直接使用cout输出,无需std::
cin.get(); // 直接使用cin获取用户输入
return 0;
}
```
在实际编写C++代码时,这两个头文件通常会放在程序开始的位置,以便后续的代码可以方便地使用输入输出功能。
#include <iostream> using namespace std; int main()
你提供的代码片段是一个基本的C++程序的开始部分。它包含了iostream头文件,并使用了命名空间std。main函数是程序的入口点,它是程序执行的起始位置。
然而,你的代码片段是不完整的,缺少了main函数的实现部分。在main函数中,你可以编写程序的逻辑代码,执行各种操作和输出。
以下是一个完整的示例程序,展示了如何使用iostream和main函数:
```c++
#include <iostream>
using namespace std;
int main()
{
// 在这里编写你的程序逻辑代码
cout << "Hello, World!" << endl; // 示例输出语句
return 0;
}
```
在这个示例中,我们在main函数中输出了一条简单的问候语句"Hello, World!",然后返回0表示程序正常结束。
你可以在main函数中编写任意的C++代码来实现你的需求。如果你有特定的问题或需要进一步的帮助,请告诉我具体需要做什么,我会尽力提供帮助。
阅读全文
相关推荐















