開発環境
- Microsoft Windows 7 Home Premium (OS)
- Microsoft Visual C# 2010 Express Edition (IDE)
- 言語: C#
独習C# 第3版 ハーバート・シルト (著) エディフィストラーニング株式会社 矢嶋聡 (監修, 翻訳) の第6章(Cメソッドとクラスの詳細)の理解度チェック1、2、3を解いてみる。
1.
問題のコードは正しくない。Xクラスのcountはprivate(記述がないときは標準のprivateになる)なので、Yクラスでは値を代入できない。
2.
アクセス修飾子は、メンバー宣言の前に指定しなければならない。
3.
コード
using System; public class Stack { private char[] s; private int loc; public Stack(int size) { s = new char[size]; loc = 0; } public Stack(Stack obj) { loc = obj.loc; s = new char[obj.s.Length]; for (int i = 0; i < s.Length; i++) { s[i] = obj.s[i]; } } public Stack(char[] a) { loc = 0; s = new char[a.Length + 1]; for (int i = 0; i < a.Length; i++) { Push(a[i]); } } public void Push(char ch) { if (loc == s.Length) { Console.WriteLine(" -- Stack is full."); return; } s[loc] = ch; loc++; } public char Pop() { if (loc == 0) { Console.WriteLine(" -- Stack is empty --."); return (char)0; } loc--; return s[loc]; } } class Tester { public void Run() { Stack s1 = new Stack(10); char[] name = { 'T', 'o', 'm' }; Stack s2 = new Stack(name); char ch; for (int i = 0; i < 10; i++) { s1.Push((char)('A' + i)); } Stack s3 = new Stack(s1); Console.Write("Contents of s1: "); for (int i = 0; i < 10; i++) { ch = s1.Pop(); Console.Write(ch); } Console.WriteLine(); Console.Write("Contents of s2: "); for (int i = 0; i < 3; i++) { ch = s2.Pop(); Console.Write(ch); } Console.WriteLine(); Console.Write("Contents of s3: "); for (int i = 0; i < 10; i++) { ch = s3.Pop(); Console.Write(ch); } Console.WriteLine(); } static void Main() { Tester t = new Tester(); t.Run(); } }
入出力結果(Console Window)
Contents of s1: JIHGFEDCBA Contents of s2: moT Contents of s3: JIHGFEDCBA 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿