我是C#编程的新手,我在一本教科书中看到了一个例子。
这个例子是关于抽象类的解释,但我不理解代码的一部分:
// Create an abstract class.
using System;
abstract class TwoDShape
{
double pri_width;
double pri_height;
// A default constructor.
public TwoDShape()
{
Width = Height = 0.0;
name = "null";
}
// Parameterized constructor.
public TwoDShape(double w, double h, string n)
{
Width = w;
Height = h;
name = n;
}
// Construct object with equal width and height.
public TwoDShape(double x, string n)
{
Width = Height = x;
name = n;
}
// Construct a copy of a TwoDShape object.
public TwoDShape(TwoDShape ob)
{
Width = ob.Width;
Height = ob.Height;
name = ob.name;
}
}
为什么以及何时构建对象的副本?
答案 0 :(得分:0)
当您的类是抽象类时,您无法使用它构造对象。你需要在其他班级上做遗产。在这里你可以像这样做一个TwoDShape的矩形类herite:
using System;
abstract class TwoDShape
{
double pri_width;
double pri_height;
// A default constructor.
public TwoDShape()
{
Width = Height = 0.0;
name = "null";
}
// Parameterized constructor.
public TwoDShape(double w, double h, string n)
{
Width = w;
Height = h;
name = n;
}
// Construct object with equal width and height.
public TwoDShape(double x, string n)
{
Width = Height = x;
name = n;
}
// Construct a copy of a TwoDShape object.
public TwoDShape(TwoDShape ob)
{
Width = ob.Width;
Height = ob.Height;
name = ob.name;
}
}
Class Rectangle:TwoDShape
{
public Rectangle(double w, double h) : base(w, h)
{
}
}