首页 > 解决方案 > 为什么我无法将指针转换为类结构

问题描述

我有一Geometry堂课

class Geometry
{
public: 
    std::string stdstrType;
    bool bValid;
public:
    Geometry()

    Geometry( std::string strType , bool bValue )

    Geometry(const Geometry &g)

    ~Geometry()     
    virtual void draw();
    bool isValid();
    void setValidState(bool bState);
    virtual void Init();
    std::string GetName();  
};

Geometry在这种情况下,哪个是对象的基Sphere

class Sph : public Geometry
{
public:
    Sph( float radius , float segments );
    ~Sph();
    void init();
    void CleanUp();
    void draw();

private:
    float fRadius, fSegments;
    bool isInited;
    unsigned int m_VAO, m_VBO;
    int iNumsToDraw;
    SumShader shader;
    bool isChanged;
};

Container我有一个包含不同对象的树结构,并且Geometry是对象中的一种数据类型Container

class Container
{
private:
    std::string stdstrContainerName;
    std::string stdstrPluginType;
    Geometry Geom;
}

由于树中的每个项目都可以包含一个圆形或矩形,所以我想使用几何的绘制功能来绘制Geometry对象类型。为此,当我尝试将任何GeometryObject 类型转换为时,Geometry我得到一个错误。

Sph sphere(0.1 , 32);
Geometry *geom = &sphere;
Container cont("Sphere" , "SPHERE" , *geometry );   
myModel->SetContainer(child, cont);

容器的构造函数

 Container::Container( std::string strName, std::string strType, const 
 Geometry& geometry) : Geom(geometry)
  { 
     stdstrContainerName = strName;
     stdstrPluginType = strType;
  }

 void  TreeModel::SetContainer(const QModelIndex &index, Container Cont)
  {
    TreeItem *item = getItem(index);
    item->setContainer(Cont);
  }


  class TreeItem
   {
    public:
     // Functions here
   private:
     QList<TreeItem*> childItems;
     Container itemData;
     TreeItem* parentItem;
   };

1)这是正确的方法吗?

2)如何将Geometry对象转换为Geometry指针?

标签: c++c++11

解决方案


Sph sphere();

您已经声明了一个返回 Sphere 对象且不带参数的函数。

要向 Sph 声明一个对象,您只需简单地编写

Sph sphere;或者Sph sphere{};

我猜你尝试了第一个但它没有编译,所以你只是更改了签名“直到编译”。您已经声明了一个自定义构造函数,这意味着编译器不再为您提供默认构造函数,因此您无法在不调用正确构造函数的情况下声明变量(在您的情况下它没有意义)。

除了与

Geometry *geom = new Geometry;
geom = &sphere;

您正在创建一个新的指针几何,而不是立即泄漏它并重新分配给一个完全没有意义的球体几何。

此外,您所有的方法在 Geometry 中都是公开的,这没有意义(为什么要公开 bool 有效然后是 getter?)。

此外,类Container持有一个基类的实例,由于对象切片会给您带来问题,您需要使用指针或引用。

为了回答您的问题,您应该使用

Geometr* geom = new Sphere(1, 5); // random numbers

但我能说的最真实和最诚实的事情是从头开始重写所有内容,然后再通过一个更简单的示例进行更多尝试。


推荐阅读