it.Phontol.com 1. 编写一个控制台应用程序,完成下列功能。it.Phontol.com
it.Phontol.com 1) 创建一个类,用无参数的构造函数输出该类的类名。it.Phontol.com
it.Phontol.com 2) 增加一个重载的构造函数,带有一个string类型的参数,在此构造函数中将传递的字符串打印出来。it.Phontol.com
it.Phontol.com 3) 在Main方法中创建属于这个类的一个对象,不传递参数。it.Phontol.com
it.Phontol.com 4) 在Main方法中创建属于这个类的另一个对象,传递一个字符串“This is a string.”。it.Phontol.com
it.Phontol.com 5) 在Main方法中声明类型为这个类的一个具有5个对象的数组,但不要实际创建分配到数组里的对象。it.Phontol.com
it.Phontol.com 6) 写出运行程序应该输出的结果。it.Phontol.com
it.Phontol.com 【解答】
it.Phontol.com以下是引用片段:
using System;
class Test1
{
public Test1()
{
Console.WriteLine(this);
}
public Test1(string str)
{
Console.WriteLine(str);
}
public static void Main()
{
Test1 t1 = new Test1();
Test1 t2 = new Test1("This is a string.");
Test1[] t3 = new Test1[5];
}
}
it.Phontol.com
输出结果:
it.Phontol.com Test1
it.Phontol.com This is a string.
it.Phontol.com 2. 编写一个控制台应用程序,定义一个类MyClass,类中包含有public、private以及protected数据成员及方法。it.Phontol.com然后定义一个从MyClass类继承的类MyMain,将Main方法放在MyMain中,在Main方法中创建MyClass类的一个对象,并分别访问类中的数据成员及方法。it.Phontol.com要求注明在试图访问所有类成员时哪些语句会产生编译错误。it.Phontol.com
it.Phontol.com 【解答】
it.Phontol.com以下是引用片段:
using System;
class MyClass
{
public int i;
private int j;
protected int k;
public void method1()
{
Console.WriteLine("public method.");
}
private void method2()
{
Console.WriteLine("private method.");
}
protected void method3()
{
Console.WriteLine("protected method.");
}
}
class MyMain : MyClass
{
public static void Main()
{
MyClass t = new MyClass();
Console.WriteLine("i={0}", t.i);
Console.WriteLine("j={0}", t.j); //会出现编译错误,私有成员不允许在其它类中访问
Console.WriteLine("k={0}", t.k); //会出现编译错误,应该创建MyMain的对象,然
//后通过MyMain的对象访问
t.method1();
t.method2(); //会出现编译错误,私有的方法不允许在其它类中调用
t.method3(); //会出现编译错误,应该创建MyMain的对象,然后通过MyMain的
//对象调用该方法
}
}
www.Phontol.com
www.Phontol.com
www.Phontol.com
[1] [2] [3] [4] [下一页]Phontol.com