【发布时间】:2018-10-17 13:05:37
【问题描述】:
我有一个任务(一堆 oop 的东西,多态性和继承),除此之外,我必须做以下事情:
我需要向 Vehicle 类添加一个抽象方法(称为 calculateOccupancy()),它必须返回车辆中剩余空间的百分比.然后我必须在我的派生类中实现它。这里的问题是,我有 3 个派生类,其中两个有 2 个属性,一个有 3 个。那么我如何制作我的抽象方法,以便它可以接受 2 或 3 个参数。
-
我要在Person类中添加一个不可更改的属性,该属性要返回名字和姓氏的第一个字母,除以一个点。
namespace Example
{
abstract class Vehicle
{
//class member variables, most likely unnecessary for the questions
private Person driver;
private string vehicleBrand;
private string vehicleType;
private double fuelConsumption;
private double gasTankSize;
private string fuelType;
//the default constructor
public Vehicle()
{}
//The abstract method from question 2
// how to make it so that it wont error when I need to
//put in 3 variables instead of two, meaning, how would I add int c
public abstract double calculateOccupancy (int a, int b);
//The derived class that implements the method
class Bus : Vehicle
{
private int allSeats;
private int allStandingSeats;
private int busPassengers; //the number of passengers
//the constructor
public Bus (int a, int b, int c)
{
allSeats=a;
allStandingSeats=b;
busPassengers=c;
}
//the abstract method
// needs to take in int b (standing seats)
public override double calculateOccupancy(int a, int c)
{
//this code calculates the leftover space in the vehicle
double busSpace=(busPassengers*100) / allSeats;
return busSpace;
//same code for the leftover standing space (int c)
}
}
}
class Person
{
protected string name;
protected string lastName;
//question 1
//properties for char gender
protected char gender;
//question 3
protected readonly string initials;
//the code errors, at the get/set
public char Gender
{
get{ return gender; }
set {gender=value;}
}
/*and the property im not sure how to make
public string Initials{}
*/
}
我希望 cmets 增加一些清晰度,而不是混淆,谢谢大家的帮助。
【问题讨论】:
-
这里没有问题。
-
什么意思?我在描述中写了它们。
-
不,您发布了该问题的要求。您是否希望我们阅读 cmets 并找出其中哪些是问题,然后编写代码 sn-ps 来发布?请阅读How to ask,并发布Minimal, Complete, Verifiable Example。请在每个帖子中限制自己一个问题,并在前面明确说明您的问题是什么。
-
@Simon #2 可能没问题,“那么我如何制作我的抽象方法,以便它可以接受 2 或 3 个参数[?]”是一个明确的问题陈述。 #1 和 #3 并不那么明显。我们看到您有问题,但由于他们没有附加任何问题,看起来您只是希望我们为您解决问题。相反,我们需要查看您提出的具体问题,以便我们为您提供具体答案。正如 Jeff 所说,您应该将帖子限制为一个问题,但只包含与该问题相关的代码。
-
我是一个新用户,我的最后一个问题被一些人否决(它非常简短直接,不知道为什么投反对票),这就是为什么我仅限于这个帖子并且不能发帖3天。所以我不得不在一篇文章中写出 3 个问题。我知道我的问题写得不好而且很长,这就是我注释掉代码的原因。无论如何感谢您的建议@JeffLearman
标签: c# .net oop inheritance properties