当我在两个类之间使用继承时,变量正在初始化

时间:2017-07-02 13:52:26

标签: class oop object initialization shapes

这是我写的代码:

public class shapess
{
    public int len1, len2, len3;
    public void SetVars (int Len1, int Len2, int Len3)
    {
        len1 = Len1;
        len2 = Len2;
        len3 = Len3;
    }
}
public class triangle : shapess
{
    shapess sh = new shapess();
    public void Perimeter()
    {
        sh.SetVars(3, 6, 9);
        int peri = len1 + len2 + len3;
        Console.WriteLine("The perimeter is: "+peri);
    }
}

当我尝试使用triangle tr = new triangle(); tr.Perimeter();播放时,它向我显示我的变量(len1,len2& len3)等于0,输出为:The perimeter is: 0。 我的问题在这里是什么?

1 个答案:

答案 0 :(得分:0)

您正在Shapess类中创建Trangle实例并设置该实例的len1,len2 ..而不是Trangle本身len1,len2的值....尝试

public class triangle : shapess
{
    public void Perimeter()
    {
        SetVars(3, 6, 9);
        int peri = len1 + len2 + len3;
        Console.WriteLine("The perimeter is: "+peri);
    }
}