3

在 D 中测试以下内容

import std.stdio;

struct S
{
    int _val;
    @property ref int val() { return _val; }
    @property void val(int v) { _val = v; writeln("Setter called!"); }
}

void main()
{
    auto s = S();
    s.val = 5;
}

产量"Settter called!"作为输出。

编译器使用什么规则来确定是调用第一个实现还是第二个实现?

4

1 回答 1

5

在这里,您提供了两种@property方法,一种接受参数,另一种不接受。在做的时候s.val = 5;,你实际上在做的是s.val(5),但是你可以把它写成一个属性而不是一个方法调用(参见valhttp://d-programming-language.org/function.html#property-functions 。从编译器可以做标准的重载决议 - 见http://d-programming-language.org/function.html#function-overloading@propertys.val(5)

于 2011-08-07T19:48:35.780 回答