您的位置:首页 > 编程语言 > C#

C# 类的定义及构造函数的重载

2015-01-24 22:12 288 查看
<span style="font-family:FangSong_GB2312;font-size:18px;">
1.类的定义及构造函数的重载

代码如下:</span>
<span style="font-family:FangSong_GB2312;font-size:18px;"> </span><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _8_4
{
class student
{
string strname;
public student(string name)
{
strname = name;
Console.WriteLine("姓名?:" + strname + " 性别: 未知" + " 年龄 : 未知");
}
public student(string name,string sex)
{
strname = name;
Console.WriteLine("姓名:" + strname + " 性别: " + sex + " 年龄: 未知");
}
public student(string name, string sex,int age)
{
strname = name;
Console.WriteLine("姓名:" + strname + " 性别: " + sex + " 年龄:" + age);
}
~student()
{
Console.WriteLine("学生信息" + strname + "输出完毕");
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("输出学生信息:");
student stu1 = new student("二狗子");
student stu2 = new student("翠花","女");
student stu3 = new student("狗剩","男",30);
Console.ReadLine();
}
}
}
运行结果:
2.方法的重载
代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace p_134{class Program{const double PI = 3.1415926;double getgriph(double r){return 2 * PI * r;}double getgriph(double width,double length){return 2 * (width + length);}static void Main(string[] args){try{Program pro = new Program();Console.WriteLine("计算圆的周长:");double dec_r = Convert.ToDouble(Console.ReadLine());Console.WriteLine("圆的周长为:" + pro.getgriph(dec_r));Console.WriteLine("输入矩形的长和宽(以逗号分隔)");string rectvalue = Console.ReadLine();string[] rectsplit = rectvalue.Split(new char[] { ',' });double dec_length = Convert.ToInt32(rectsplit[0]);double dec_width = Convert.ToInt32(rectsplit[1]);Console.WriteLine("矩形的周长为:   " + pro.getgriph(dec_length, dec_width));}catch (Exception e) { Console.WriteLine(e.Message); }Console.ReadLine();}}}
运行结果:
3.定义一个类,描述一个矩形,包含有长、宽两种属性,有一个无参数构造方法,对长宽赋初值为10,8;一个带两个参数方法,对长宽赋值;一个计算面积方法。编写一个测试类,对以上类进行测试,创建一个长方形,定义其长、宽,输出其面积。<span style="font-family:FangSong_GB2312;font-size:18px;">using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace 类与对象{class rect{double rect_length ;double rect_width ;public double Rect_width{get { return rect_width; }set { rect_width = value; }}public double Rect_length{get { return rect_length; }set { rect_length = value; }}public void rect_shape(){rect_length = 10;rect_width = 8;}public double getarea(){return rect_length * rect_width;}static void Main(string[] args){rect shape = new rect();shape.rect_shape();Console.WriteLine("默认矩形的面积:" + shape.getarea());Console.WriteLine( );shape.rect_length = 100;shape.rect_width = 80;Console.WriteLine("矩形的长" + shape.Rect_length);Console.WriteLine("矩形的宽" + shape.Rect_width);Console.WriteLine("矩形的面积:" + shape.getarea());Console.ReadLine();}}}</span>运行结果:

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: