c++ - 为什么我无法将指针转换为类结构
问题描述
我有一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
对象类型。为此,当我尝试将任何Geometry
Object 类型转换为时,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
指针?
解决方案
和
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
但我能说的最真实和最诚实的事情是从头开始重写所有内容,然后再通过一个更简单的示例进行更多尝试。
推荐阅读
- android - RxJava2 更改 API 返回的 Flowable 对象的类型
- spring - 无法打开 ServletContext 资源 - applicationContext.xml
- google-chrome-extension - (如何)Chrome 扩展程序可以侦听来自我的服务器的消息吗?
- c# - DataContractJsonSerializer 和缺少 [ ] 的文件
- java - 为什么 ViewPager 不在 RelativeLayout 内滑动?
- tfs - Katalon TFS CI 管道/发布管理
- java - Spring boot 2.04 Jackson 无法将 LocalDateTime 序列化为 String
- c# - .Net Web Api 获取方法
- c# - 实体框架如何提高查询多个关系表的性能?
- elasticsearch - 在 Elastic Search 中使用完成建议器查询检查不为空