以下程序创建弦乐器Stringed类的对象,调用play()方法进行演奏。(注意:两个空中的答案必需依次分两行书写!) public class Music { public static void main(String[] args) { Instrument test1= ; ; //由弦乐器实现演奏 } }
时间: 2023-06-01 10:01:53 浏览: 65
public class Music {
public static void main(String[] args) {
Instrument test1 = new Stringed(); //由弦乐器实现演奏
test1.play();
}
}
相关问题
以下程序由弦乐器类Stringed实现乐器接口Instrument,并实现接口中的抽象方法。(注意:两个空中的答案必需依次分两行书写!) class Stringed { void play() { System.out.println("Stringed.play()"); } }
class Stringed implements Instrument {
void play() {
System.out.println("Stringed.play()");
}
}
修改下列代码include using namespace std; enum NOTE{middleC,Csharp,Cflat}; class instrument{public:virtual void play(NOTE)const=0; virtual char*what()const=0; virtual void adjust(int)=0; }; class Wind:public instrument{public:void play(NOTE)const{cout<<1<<endl}; char*what()const{return"Wind";} void adjust(int){} }; class Percussion:public instrument{public:void play(NOTE)const{cout<<2<<endl}; char*what()const{return"Percussion";} void adjust(int){} }; class Stringed:public instrument{public:void play(NOTE)const{cout<<3<<endl}; char*what()const{return"Stringed";} void adjust(int){} }; class Brass:public Wind{public:void play(NOTE)const{cout<<11<<endl}; char*what()const{return"Barss";} }; class Woodwind:public instrument{public:void play(NOTE)const{cout<<12<<endl}; char*what()const{return"Woodwind";} }; void tune(instrument&i){i.adjust(1);} int main() Wind flute; Percussion drum; String violin; Brass flugelhorn; Woodwind recorder; tune(flute); tune(drum); tunea(flugelhorn); tune(recorder); f(flugelhorm); return 0;}
这段代码还是存在一些语法错误,我做如下修改:
```
#include <iostream>
using namespace std;
enum NOTE{middleC,Csharp,Cflat};
class instrument{
public:
virtual void play(NOTE)const=0;
virtual char*what()const=0;
virtual void adjust(int)=0;
};
class Wind:public instrument{
public:
void play(NOTE)const{cout<<1<<endl;}
char*what()const{return"Wind";}
void adjust(int){}
};
class Percussion:public instrument{
public:
void play(NOTE)const{cout<<2<<endl;}
char*what()const{return"Percussion";}
void adjust(int){}
};
class Stringed:public instrument{
public:
void play(NOTE)const{cout<<3<<endl;}
char*what()const{return"Stringed";}
void adjust(int){}
};
class Brass:public Wind{
public:
void play(NOTE)const{cout<<11<<endl;}
char*what()const{return"Brass";}
};
class Woodwind:public instrument{
public:
void play(NOTE)const{cout<<12<<endl;}
char*what()const{return"Woodwind";}
};
void tune(instrument&i){i.adjust(1);}
int main() {
Wind flute;
Percussion drum;
Stringed violin;
Brass flugelhorn;
Woodwind recorder;
tune(flute);
tune(drum);
tune(flugelhorn);
tune(recorder);
//f(flugelhorn); // 这行代码没有意义,可以删除
return 0;
}
```
修改后的代码应该输出:
1
2
11
12
因为在 tune() 函数中,对于每个乐器都调用了其 adjust() 函数,而在 main() 函数中,每个乐器都被传入了 tune() 函数中进行调音。在 play() 函数中,Wind 类和 Brass 类重载了父类的 play() 函数,并输出了不同的数字,因此输出结果为 1、2、11、12。
阅读全文