내 기본 클래스의 개체 'spot'에 'main'메서드를 만들었습니다. 4 개의 속성, 'Animal'클래스 생성자 및 기능 'SaySomething'. 내 개체 '자리'초기화에 대한 클래스 생성자 '동물'자신의 매개 변수를 전달합니다. 또한 기본 클래스 'Animal'속성과 메서드를 상속받은 파생 클래스 'Dog'를 만들었으며 'main'메서드에서 'grover'개체를 만들고 ' grover '객체가 상속 된 메소드'SaySomething '을 호출하면 내 프로그램에서 예외가 발생합니다.'ConsoleApplication1.Animal '에는 프로그램을 실행하려고 할 때 0 개의 인수를 사용하는 생성자가 포함되어 있지 않습니다.내 C# 파생 클래스는 기본 클래스 속성 및 함수를 상속하지만 예외가 throw됩니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Animal
{
public double height { get; set; }
public double weight { get; set; }
public string sound { get; set; }
public string name { get; set; }
public Animal(double height, double weight, string name, string sound)
{
this.height = height;
this.weight = weight;
this.name = name;
this.sound = sound;
}
public void SaySomething()
{
Console.WriteLine("{0} is {1} inches tall, weighs {2} lbs and likes to say {3}", name, height, weight, sound);
}
}
class Dog : Animal
{
}
class Program
{
static void Main(string[] args)
{
Animal spot = new Animal(16,10,"spot","woof");
Dog grover = new Dog();
grover.SaySomething();
}
}
}
클래스 생성자를 삭제하고 프로그램에서 실행할 수있는 개체 매개 변수와 인수를 찾아야한다는 것을 알고 있습니다. 그러나이 코드의 문제점은 무엇입니까? 왜 내 프로그램을 실행할 수 없습니까? 그리고 다른 초기화 방법을 선택해야합니까, 아니면 작동을 위해이 코드를 향상시킬 수 있습니까?
컴파일하지 않아야합니다. Animal에는 매개 변수없는 생성자가 없으므로 Dog 클래스는 자체 생성자에서 해당 생성자를 호출해야합니다. – Silvermind
@Silvermind 컴파일되지 않습니다. OP가 그것을 "예외"로 잘못 식별하고 있습니다. –