問題6:virtualと仮想関数
| この問題を解くためには… |
| → 応用編第7日目参照 |
|---|
probex7-1.(難易度:★)
listex7-1に出ているlistex7-1をもとにして、三次元ベクトルクラス、Vector3クラスを作り、実行結果が以下のようになるようにプログラムを作り変えなさい。
そこで、これら2つのクラスに共通するメンバを、飛行機(AirPlane)クラスに集約し、FighterAiracraftクラス、およびPassengerPlaneは、それらのクラスを継承したものにするように、プログラムを書きかかえなさい。ただし、この時、AirPlaneは、完全仮想関数fly()を持つ抽象クラスとすること。
期待される実行結果
v1=(1,2,3)
v2=(1,2,3)
v1 + v2=(2,4,6)
v3=(4,8,12)
v1=(5,10,15)
v2=(0,0,0)
v2=(1,2,3)
v1 + v2=(2,4,6)
v3=(4,8,12)
v1=(5,10,15)
v2=(0,0,0)
probex7-2.(難易度:★★★)
以下のプログラムは、文字列を扱うクラス、NewStringクラスと、それを用いたサンプルの実行結果である。このプログラムを指定したように変更し、期待される実行結果を得られるようにしなさい。
NewString.h
#ifndef _NEWSTRING_H_
#define _NEWSTRING_H_
#include <iostream>
#include <string>
using namespace std;
class NewString{
private:
// 文字列
string m_value;
public:
// コンストラクタ
NewString();
// 値を代入するコンストラクタ①(文字列から)
NewString(string value);
// 値を代入するコンストラクタ②(他のクラスから)
NewString(NewString& value);
// 値を代入
NewString& operator= (NewString& n);
// stringで値を取得
string getValue();
};
#include "NewString.h"
// コンストラクタ
NewString::NewString()
{
m_value = "";
}
// 値を代入するコンストラクタ①(文字列から)
NewString::NewString(string value)
{
m_value = value;
}
// 値を代入するコンストラクタ②(他のクラスから)
NewString::NewString(NewString& value)
{
m_value = value.getValue();
}
// 値を代入
NewString& NewString::operator= (NewString& n)
{
m_value = n.getValue();
return *this;
}
// stringで値を取得
string NewString::getValue()
{
return m_value;
}
#include <iostream>
#include <string>
#include "NewString.h"
using namespace std;
int main(){
NewString s1("HelloWorld"),s2;
cout << s1.getValue() << endl;
s2 = s1; // 値を代入
cout << s2.getValue() << endl;
NewString s3(s2); // NewStringを引数としてコンストラクタ呼び出し
cout << s3.getValue() << endl;
NewString s4("HELLOWORLD");
cout << s4.getValue() << endl;
return 0;
}
s1 = HelloWorld
s2 = HelloWorld
s3 = HelloWorld
s4 = HELLOWORLD
s2 = HelloWorld
s3 = HelloWorld
s4 = HELLOWORLD
変更の方針
- NewStringクラスに、==演算子を定義し、NewStringクラスの文字列との比較をできるようにしなさい。
- NewStringクラスが等しくなる条件は、英単語の場合、大文字と小文字を同一と見なすよにしなさい。(例えば、apple、Apple、APPLEなどは、すべて等しいとみなす)
- 以上の変更を加えたうえで、main.cppを以下のように変更しなさい。
#include <iostream>
#include <string>
#include "NewString.h"
using namespace std;
int main(){
NewString s1("HelloWorld"),s2;
cout << s1.getValue() << endl;
s2 = s1; // 値を代入
cout << s2.getValue() << endl;
NewString s3(s2); // NewStringを引数としてコンストラクタ呼び出し
cout << s3.getValue() << endl;
NewString s4("HELLOWORLD");
cout << s4.getValue() << endl;
if(s1 == s2){
cout << "s1==s2" << endl;
}
if(s1 == s4){
cout << "s1==s4" << endl;
}
return 0;
}
s1 = HelloWorld
s2 = HelloWorld
s3 = HelloWorld
s4 = HELLOWORLD
s1==s2
s1==s4
s2 = HelloWorld
s3 = HelloWorld
s4 = HELLOWORLD
s1==s2
s1==s4









