I'm having some trouble with using the conditional operator to get a reference to an object. I have the a setup similar to this:
class D
{
virtual void bla() = 0;
};
class D1 : public D
{
void bla() {};
};
class D2 : public D
{
void bla() {};
};
class C
{
public:
C()
{
this->d1 = new D1();
this->d2 = new D2();
}
D1& getD1() {return *d1;};
D2& getD2() {return *d2;}
private:
D1 *d1;
D2 *d2;
};
int main()
{
C c;
D& d = (rand() %2 == 0 ? c.getD1() : c.getD2());
return 0;
}
When compiling, this gives me the following error:
WOpenTest.cpp: In function 'int
main()': WOpenTest.cpp:91: error: no
match for conditional 'operator?:' in
'((((unsigned int)rand()) & 1u) == 0u)
? c.C::getD1() : c.C::getD2()'
I understand this is illegal according to the C++ standard (as seen in this blog post), but I don't know how to get my reference to D
without using the conditional operator.
Any ideas?
The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. Syntax: The conditional operator is of the form. variable = Expression1 ? Expression2 : Expression3.
A conditional operator is a single programming statement, while the 'if-else' statement is a programming block in which statements come under the parenthesis. A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement cannot be used for the assignment purpose.
As conditional operator works on three operands, so it is also known as the ternary operator. The behavior of the conditional operator is similar to the ' if-else ' statement as 'if-else' statement is also a decision-making statement.
Since the Conditional Operator ‘?:’ takes three operands to work, hence they are also called ternary operators. Here, Expression1 is the condition to be evaluated.
Cast to D&
within both branches:
D& d = (rand() %2 == 0 ? static_cast<D&>(c.getD1()) : static_cast<D&>(c.getD2()));
Btw, you don't really need to use a conditional operator,
D* dptr; if(rand() %2 == 0) dptr = &c.getD1(); else dptr = &c.getD2();
D& d = *dptr;
would work too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With