【发布时间】:2020-02-02 23:52:12
【问题描述】:
我是 C# 的初学者,正在尝试让我的第二个类 MyCalc2 继承自 MyCalc。但我遇到以下关于 MyCalc2 的错误消息:
没有给出与'MyCalc.MyCalc(int, int, string, string)'的所需形式参数'x'相对应的参数
这里的目标是添加另一个继承自基类的类。
我知道我需要在我的基类中添加类似 'MyCalc: base(x)' 的内容,但我不知道放置参数的位置(如果这甚至是正确的做法)。任何指导将不胜感激。这是我目前所拥有的:
using System;
class MyCalc
{
// class variable
public int x;
public int z;
public string y;
public string n;
// constructor
public MyCalc(int x, int z, string y, string n)
{
this.x = x; // assign the parameter passed to the class variable
this.z = z;
this.y = y;
this.n = n;
}
// calculate the operations
public int GetAdd()
{
return (this.x + this.z);
}
public int GetSubtract()
{
return (this.x - this.z);
}
public int GetMultiply()
{
return (this.x * this.z);
}
public int GetDivide()
{
return (this.x / this.z);
}
public string GetYes()
{
return (this.y);
}
public string GetNo()
{
return (this.n);
}
}
class MyCalc2:MyCalc //where the error is occurring
{
static void Main(string[] args)
{
bool repeat = false;
do
{
repeat = false;
int x = 0; int z = 0; string y; string n;
Console.WriteLine("Enter the First Number");
x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the Second Number");
z = Convert.ToInt32(Console.ReadLine());
//Using a switch statement to perform calculation:
Console.WriteLine("Enter operator\r");
switch (Console.ReadLine())
{
case "+":
Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
break;
case "-":
Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
break;
case "*":
Console.WriteLine($"The Answer is: {x} + {z} = " + (x + z));
break;
case "/":
Console.WriteLine($"The Answer is: {x} - {z} = " + (x - z));
break;
}
//Repeat or Exit program using the do-while loop:
string input = Console.ReadLine();
Console.WriteLine("Do you want another operation(Y / N) ?");
input = Console.ReadLine();
repeat = (input.ToUpper() == "Y");
}
while (repeat);
Console.WriteLine("Thanks for using our system.");
Console.ReadKey();
}
}
【问题讨论】:
-
为什么
MyCalc2继承自MyCalc?它不会扩展或覆盖MyCalc的任何方法。我怀疑你想在你的MyCalc2中使用new MyCalc(something),而不是从它继承。 -
您可能需要重新考虑您的设计,继承可能不适合这里。
-
您可能不应该将 Main 方法包含为 MyClass2 的成员。你是故意这样做的吗?继承应该非常严格地保留在可以说“Childclass is an ParentClass”的情况下。在所有其他情况下,使用继承可能不是一个好主意。我建议只踢出 MyVals2:MyCalc 行,确保所有学徒匹配。您可能会尝试创建一个控制台应用程序。 Main 是入口点,它可能运行良好。
标签: c# class inheritance