代码之家  ›  专栏  ›  技术社区  ›  laura

条件运算符问题

  •  8
  • laura  · 技术社区  · 16 年前

    我在使用条件运算符获取对象引用时遇到一些问题。我有一个类似的设置:

    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;    
    }
    

    编译时,出现以下错误:

    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()'
    

    根据C++标准,我理解这是非法的。 as seen in this blog post ,但我不知道如何找到我的参考资料 D 不使用条件运算符。

    有什么想法吗?

    3 回复  |  直到 16 年前
        1
  •  14
  •   Johannes Schaub - litb    16 年前

    铸造成 D& 在两个分支中:

    D& d = (rand() %2 == 0 ? static_cast<D&>(c.getD1()) : static_cast<D&>(c.getD2()));
    
        2
  •  2
  •   Ether    16 年前

    顺便说一句,你不需要使用条件运算符,

    D* dptr; if(rand() %2 == 0) dptr = &c.getD1(); else dptr = &c.getD2();
    D& d = *dptr;
    

    也会工作。

        3
  •  0
  •   shyam    16 年前

    或者可以将函数的返回类型更改为基类。