简体   繁体   English

c++ 条件表达式赋值参考

[英]c++ conditional expression assign reference

using namespace std;
class A {
    public:
        virtual int r();
};

class B : public A {
    public:
        int r() { return 1; }
};

class C : public A {
    public:
        int r() { return 2;}
};

int main(int argc, char ** argv) {
    B b;
    C c;
    A &a = argc > 1 ? b : c;
    return a.r();
}

with errors:有错误:

#g++ a.cc
a.cc: In function ‘int main(int, char**)’:
a.cc:20:18: error: operands to ‘?:’ have different types ‘B’ and ‘C’
   20 |  A &a = argc > 1 ? b : c;
      |         ~~~~~~~~~^~~~~~~

How can I fix it to bind the reference to either of the two objects?如何修复它以将引用绑定到两个对象中的任何一个?

It's just the way the language works, that's all.这只是语言的工作方式,仅此而已。 Note that you can't static_cast from a B to a C either (or vice-versa) which, informally speaking, is required for the branch types of the ternary conditional operator.请注意,您不能从B C static_cast或反之亦然),非正式地说,这是三元条件运算符的分支类型所必需的。

You need to write something like你需要写类似的东西

A &a = argc > 1 ? static_cast<A&>(b) : static_cast<A&>(c);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM