Thread overview | ||||||
---|---|---|---|---|---|---|
|
May 20, 2012 static functions? | ||||
---|---|---|---|---|
| ||||
I pretty sure I'm an idiot. [code] class foo { public static int bar() { return 0; } } [/code] How do I call bar() without creating an instance of foo? foo.bar() results in "Error: undefined identifier 'bar'" I'm having a really hard time finding anything related to D in general. |
May 20, 2012 Re: static functions? | ||||
---|---|---|---|---|
| ||||
Posted in reply to p0xel | This seems to work when the class is in the same file as main(), but if I move it to it's own file and use "import foo" it errors. What am I missing? |
May 20, 2012 Re: static functions? | ||||
---|---|---|---|---|
| ||||
Posted in reply to p0xel | On Sunday, 20 May 2012 at 21:19:14 UTC, p0xel wrote:
> This seems to work when the class is in the same file as main(), but if I move it to it's own file and use "import foo" it errors. What am I missing?
When you write "import foo;" and then foo.bar, the compiler thinks that
you a referring to a global function bar in module foo. To call static function bar of class foo in module foo write foo.foo.bar(). Or you could write "import foo : foo;" to import just the class foo from module foo and not the entire module.
|
May 21, 2012 Re: static functions? | ||||
---|---|---|---|---|
| ||||
Posted in reply to jerro | On 5/21/2012 6:32 AM, jerro wrote:
> On Sunday, 20 May 2012 at 21:19:14 UTC, p0xel wrote:
>> This seems to work when the class is in the same file as main(), but
>> if I move it to it's own file and use "import foo" it errors. What am
>> I missing?
>
> When you write "import foo;" and then foo.bar, the compiler thinks that
> you a referring to a global function bar in module foo. To call static
> function bar of class foo in module foo write foo.foo.bar(). Or you
> could write "import foo : foo;" to import just the class foo from module
> foo and not the entire module.
Or even better, name your module foo.d, and name your class Foo. Then...
import foo;
void main()
{
Foo.bar();
}
That's also the general convention.
|
Copyright © 1999-2021 by the D Language Foundation