0

我尝试了解Aliasing并遇到这个例子:

public class A
{
    // Instance variable 
    private double _x;

    // 3 constructors 

    public A(double x)
    {
        _x = x;
    }

    public A()
    {
        _x = 0;
    }

    public A(A a)
    {
        _x = a._x;
    }

    // methods 
    public double getX()
    {
        return _x;
    }

    public void setX(double x)
    {
        _x = x;
    }

    public String toString()
    {
        return "A:" + _x;
    } 
}

static void Main(string[] args)
{
    A a1 = new A(7);
    A a2 = new A(a1);
    A a3 = a2;

    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    a1.setX(10);
    Console.WriteLine("after setting 10 to a1:");
    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    a3.setX(5);
    Console.WriteLine("after setting 5 to a3:");
    Console.WriteLine("a1 = " + a1.toString());
    Console.WriteLine("a2 = " + a2.toString());
    Console.WriteLine("a3 = " + a3.toString());

    Console.ReadLine();
}

第一个Console.WriteLine和第一个SetX是 clrea 但为什么之后a3.setX(5)a2 也改变了?根据声明A a3 = a2和 SetX 参考a3

4

1 回答 1

2

两者a2a3都是对同一对象的引用。由于您有一个对象(以及对它的两个引用),因此通过任何引用更改对象将再次通过任何引用产生可见的更改。


¹这里的参考是 Java 行话,在 C/C++ 中称为指针。当您在这些语言中使用指针别名时,您的示例将显示相同的行为。

于 2013-10-30T12:47:50.530 回答