ref int value() { return m_value; } - uses?
Jonathan M Davis
jmdavisProg at gmx.com
Fri Jul 29 16:23:55 PDT 2011
On Saturday 30 July 2011 10:57:39 Joel Christensen wrote:
> What use is the property thing?
>
> class Test {
> private int m_value;
> @property ref int value() { return m_value; }
> }
>
> void main() {
> auto test = new Test;
> test.value += 1;
> }
>
> Or this:
> import std.stdio: writeln;
> import std.conv: to;
>
> class Test {
> private string m_text;
>
> ref auto text( string tx ) {
> if ( tx.length > 4 )
> m_text = m_text[ 0 .. 4 ];
> return m_text;
> }
>
> override string toString() {
> return text( m_text );
> }
> }
>
> void main() {
> auto test = new Test;
> with( test ) {
> text( to!string( test ) ) = "feet";
> writeln( test );
> text( to!string( test ) ) ~= "@";
> writeln( test );
> }
> }
http://www.d-programming-language.org/property.html
@property makes it so that the function is used syntactically as a variable
rather than a function. And while it's not currently enforced, eventually, you
will _have_ to use property functions with the variable syntax. For instance,
empty on ranges is marked with @property:
assert(range.empty);
You could currently do
assert(empty(range));
but eventually that will be illegal. Property functions allow you to have
public member variables become functions (or functions become public member
variables) without having to change the code which uses them. They're
generally used instead of getters and setters.
In this particular case, the property function returns a ref, so it's both a
getter and a setter.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list