【问题标题】:Type-cast overloading类型转换重载
【发布时间】:2017-09-16 04:07:13
【问题描述】:

当我进行这种类型转换时,我需要抛出一个异常:(B*)a其中 a 是指向基类 A 的对象的指针,而 B 是派生类。

class A
{
    protected:
        int a;
    public:
        operator B*()
        {
            throw(1);
        }

};

class B: public A
{
 protected:
    int b;
};

void main()
{
    A *a;
    (B*)a;
}

我尝试重载,但它不适用于指向 A 的指针,只能用于对象。如何重载此操作以使其与指向我的基类的指针一起工作?

【问题讨论】:

  • 对不起,我的英语很差,我试过俄语版的 stackoverflow,但没有找到答案
  • 您为什么要这样做?无论如何,你真的不能因为aA*,而不是A,你不能重载A*operator B*
  • @VittorioRomeo 我的任务是在我为此进行类型转换时抛出异常。B 类必须是派生的,A 类必须是基类。没有提到我必须使用重载,但我认为它可以工作。
  • @VittorioRomeo 也尝试过动态转换,但似乎不会为指针生成异常,仅适用于链接
  • operator B *()A 类型的对象转换为B *。它不会将A* 转换为B*。后者无法通过运算符重载来实现(指针没有成员函数)。

标签: c++ operator-overloading typecast-operator


【解决方案1】:

您只能为类提供自定义转换器,而不能为指针提供。但是您可以创建一个模拟指针的类(这就是 智能指针 的工作方式)。

这是一个此类的示例:

#include <iostream>

class A
{
protected:
    int a;
public:
    int getA() {
        return a;
    }
    virtual ~A() {}  // intended to be derived
};

class B;  // forward declaration

class Astar { // mimics a A*
private:
    A* pa;
public:
    Astar(A* p): pa(p) {}
    A* operator ->() {
        return pa;
    }
    operator B* ();  // declare the custom conversion operator
    A& operator *() {
        return *pa;
    }
};

class B: public A
{
protected:
    int b;
public:
    B(int a, int b): b(b) {
        A::a = a;
    }
    int getB() {
        return b;
    }
};

Astar::operator B*() {            // defines the custom conversion
    return dynamic_cast<B *>(pa);
}

int main()
{
    B b(1,2);
    Astar x(&b);       // x acts exactly as a A* would:
    std::cout << x->getA() << " - " << (*x).getA() << std::endl;

    B* pb = x;         // conversion to a plain B* is automatic
    std::cout << pb->getB() << std::endl;
    return 0;
}

编译时没有警告并且输出如预期的那样...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 2013-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多