June 07, 2004 Subclasses in ()?():() statements | ||||
|---|---|---|---|---|
| ||||
// the classes:
private class Master{}
private class Foo : Master{}
private class Bar : Master{}
public static int main(char[][] args){
bit isBar;
bit isFoo;
// valid and compiles:
Master a = (isBar) ? (new Bar()) : (new Master());
Master b = (isFoo) ? (new Foo()) : (new Master());
// valid, but fails to compile:
Master c = (isBar) ? (new Bar()) : (new Foo());
return 0;
}
| ||||
June 13, 2004 Re: Subclasses in ()?():() statements | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Thomas Kuehne | "Thomas Kuehne" <thomas-ThisIsSpam@kuehne.cn> wrote in message news:ca1m8u$2ogp$1@digitaldaemon.com... > // the classes: > private class Master{} > private class Foo : Master{} > private class Bar : Master{} > > public static int main(char[][] args){ > > bit isBar; > bit isFoo; > > // valid and compiles: > Master a = (isBar) ? (new Bar()) : (new Master()); > Master b = (isFoo) ? (new Foo()) : (new Master()); > > // valid, but fails to compile: > Master c = (isBar) ? (new Bar()) : (new Foo()); This is not valid. The semantics of the ternary operator stipulate that the expression as a whole has the type of the second sub-expression. Hence, your statement is exactly equivalent to Master c = (isBar) ? cast(Bar)(new Bar()) : (new Foo()); which is obviously not valid. The fix is obvious Master c = (isBar) ? cast(Master)(new Bar()) : (new Foo()); | |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply