【发布时间】:2020-08-25 07:14:24
【问题描述】:
类型定义
using System;
public enum Direction { Right, Left, Forward };
class Chaharpa
{
private int age;
private int height;
private int cordinates_x;
private int cordinates_y;
public Chaharpa(int a, int b, int x, int y)
{
age = a;
height = b;
cordinates_x = x;
cordinates_y = y;
}
public Chaharpa(int c, int d)
{
age = c;
height = d;
cordinates_x = 0;
cordinates_y = 0;
}
public int Age
{
get { return age; }
}
public int Height
{
get { return height; }
}
public int Cordinates_x
{
get { return cordinates_x; }
set { cordinates_x = value; }
}
public int Cordinates_y
{
get { return cordinates_y; }
set { if (value > 0) cordinates_y = value; }
}
public void Move(Direction direction)
{
if (direction == Direction.Forward)
Cordinates_y++;
else if (direction == Direction.Right)
Cordinates_x++;
else if (direction == Direction.Left)
Cordinates_x--;
}
class horse : Chaharpa
{
public bool is_wild;
public void Jump(int x)
{
x = Cordinates_y;
Cordinates_y += 5;
}
public void Print()
{
Console.WriteLine("Horse Information: Age," + Age + ", Height: " + Height + ", Wild: " + is_wild + ", X: " + Cordinates_x + ", Y: " + Cordinates_y);
}
}
}
用法
class Program
{
static void Main(string[] args)
{
int age, x, y, minAge = 0;
int height;
bool wild;
for (int i = 0; i < 3; i++)
{
Console.WriteLine("Horse #" + (i + 1));
Console.Write("Enter Age: ");
age = int.Parse(Console.ReadLine());
Console.Write("Enter Height: ");
height = int.Parse(Console.ReadLine());
Console.Write("Enter X: ");
x = int.Parse(Console.ReadLine());
Console.Write("Enter Y: ");
y = int.Parse(Console.ReadLine());
Console.Write("Is Wild: ");
wild = bool.Parse(Console.ReadLine());
minAge = age;
if (minAge > age)
{
minAge = age;
}
}
Console.WriteLine();
horse ob = new horse();
ob.Jump(minAge);
ob.move();
ob.Print();
Console.ReadKey();
}
}
我在 Visual Studio 中遇到这些错误:
'Chaharpa' 不包含带 0 个参数的构造函数
找不到类型或命名空间名称“horse”(您是否缺少 using 指令或程序集引用?)
找不到类型或命名空间名称“horse”(您是否缺少 using 指令或程序集引用?)
【问题讨论】:
-
Class
horse是 嵌套 在 classChaharpa中的,它不是公开的。因此,它在 Main 中不可见。使其成为公开的一级课程(对于初学者)。然后你从 Chaharpa 派生horse(应该是Horse),而不指定 CTOR。这就是为什么将为您创建一个默认 ctor,它会尝试调用其父级(默认)ctor,它不存在,因为您定义了两个参数化 ctor。 -
Chaharpa没有采用 0 个参数的构造函数。它有带有 2 或 4 个参数的构造函数。horse类必须调用其中之一,但甚至没有自己的构造函数 -
如果在一个类(马类)中不声明任何构造函数,编译器会自动提供一个公有参少构造函数(没有参数少构造函数就是Chaharpa类)。
-
c# 的命名约定:PublicThingsPascalCase、nonPublicThingsCamelCase,避免在包含小写字母的名称中使用下划线
-
这是请求。马类错了。
标签: c# class constructor