| この問題を解くためには… |
| → 応用編第1日目参照 |
|---|
問題1:コンストラクタ
prob1-1.(難易度:★)
以下のプログラムのSampleクラスにコンストラクタを追加し、期待される実行結果が得られるようにしなさい。
プロジェクトProblemex1_1/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problemex1_1
{
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
s.foo();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problemex1_1
{
class Sample
{
public void foo()
{
Console.WriteLine("foo");
}
}
}
foo
期待される実行結果
コンストラクタ ← コンストラクタで表示される
foo
foo
prob1-2.(難易度:★)
以下のプログラムは、二つの整数の和を表示するクラスCalcのインスタンスを生成し、利用したものである。ただし、このままではプログラムは正常に動作しない。Calc.csに、適切なコンストラクタを追加し、期待された実行結果のようになるようにプログラムを変更しなさい。
プロジェクトProblemex2_2/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problemex1_2
{
class Program
{
static void Main(string[] args)
{
Calc c1 = new Calc(),c2 = new Calc(3,1);
c1.Num1 = 1;
c1.Num2 = 2;
// 加算の結果を表示
c1.ShowAdd();
c2.ShowAdd();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problemex1_2
{
class Calc
{
// 一つ目の数
private int num1;
// 二つ目の数
private int num2;
// 一つ目の数のプロパティ
public int Num1
{
set { num1 = value; }
get { return num1; }
}
// 二つ目の数のプロパティ
public int Num2
{
set { num2 = value; }
get { return num2; }
}
public void ShowAdd()
{
Console.WriteLine("{0} + {1} = {2}", num1, num2, num1 + num2);
}
}
}
1 + 2 = 3
3 + 1 = 4
3 + 1 = 4
prob1-3.(難易度:★)
以下のプログラムのSampleクラスに、デストラクタを追加し、以下に示す期待される実行結果を得られるようにプログラムを改造しなさい。
プロジェクトProblemex1_3/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problemex1_3
{
class Program
{
static void Main(string[] args)
{
Sample s = new Sample();
s.func();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Problemex1_3
{
class Sample
{
public Sample()
{
Console.WriteLine("スタート");
}
public void func()
{
Console.WriteLine("func");
}
}
}
スタート
func1
期待される実行結果
func1
スタート
func1
エンド
func1
エンド









