相关疑难解决方法(0)

在C++中存储类型

是否可以将类型名称存储为C++变量?例如,像这样:

type my_type = int; // or string, or Foo, or any other type
void* data = ...;
my_type* a = (my_type*) data;
Run Code Online (Sandbox Code Playgroud)

我知道有99.9%的时间有更好的方法来做你想做的事情而不需要使用无效指针,但我很好奇C++是否允许这样的事情.

c++ types casting

29
推荐指数
4
解决办法
4万
查看次数

协变返回类型和类型转换

s->duplicate()返回一个类型的对象Box*,但是我在初始化时遇到错误Box*.看起来它正在被转换回来Shape*.如果将协变返回类型转换回基类指针,有什么意义?:

struct Shape
{
    virtual Shape* duplicate()
    {
        return new Shape;
    }
};

struct Box : Shape
{
    virtual Box* duplicate()
    {
        return new Box;
    }
};

int main()
{
    Shape* s = new Box;
    Box*   b = s->duplicate();
}
Run Code Online (Sandbox Code Playgroud)

错误:

main.cpp:22:12: error: cannot initialize a variable of type 'Box *' with an rvalue of type 'Shape *'
    Box*   b = s->duplicate();
           ^   ~~~~~~~~~~~~~~
1 error generated.
Run Code Online (Sandbox Code Playgroud)

c++ covariance dynamic-dispatch

8
推荐指数
2
解决办法
866
查看次数

标签 统计

c++ ×2

casting ×1

covariance ×1

dynamic-dispatch ×1

types ×1