铸造VEC *为double * [英] Casting a Vec* to a double*

查看:129
本文介绍了铸造VEC *为double *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解我已经提供了一个框架,慢慢调试它。在我来说,我有VEC的数组,指针记忆:

I am trying to understand a framework I have been provided with and slowly debugging it. In my case I have an array of Vec, memorized with a pointer:

Vec *cx =....;

我的VEC是定义的结构如下:

My Vec is a struct defined as follows:

struct Vec {
    double x, y, z;                  // position, also color (r,g,b)
    Vec(double x_ = 0, double y_ = 0, double z_ = 0){ x = x_; y = y_; z = z_; }
    Vec operator+(const Vec &b) const { return Vec(x + b.x, y + b.y, z + b.z); }
    Vec operator-(const Vec &b) const { return Vec(x - b.x, y - b.y, z - b.z); }
    Vec operator-() const { return Vec(-x, -y, -z); }
    Vec operator*(double b) const { return Vec(x*b, y*b, z*b); }
    Vec mult(const Vec &b) const { return Vec(x*b.x, y*b.y, z*b.z); }
    Vec& norm(){ return *this = *this * (1 / sqrtf(x*x + y*y + z*z)); }
    double dot(const Vec &b) const { return x*b.x + y*b.y + z*b.z; } // cross:
    Vec operator%(Vec&b){ return Vec(y*b.z - z*b.y, z*b.x - x*b.z, x*b.y - y*b.x); }
    double max() const { return x>y && x>z ? x : y > z ? y : z; }
};

我想知道,如果我投VEC的数组double数组中到底发生了什么。在实践中:

I would like to know what actually happens if I cast an array of Vec to an array of doubles. In practice:

double * cast = (double*)cx;

这是什么给我回来吗?

What does it give me back?

为了理解,我试图做到这一点:

In order to understand, I tried to do this:

Vec boh = Vec(1.0, 1.0, 1.0);
Vec boh2 = Vec(2.0, 2.0, 2.0);
Vec * try = new Vec[2];
try[0] = boh;
try[1] = boh2;
double* try2= (double*)try;

我认识到,试图指向第一个VEC,这是boh1,所以如果我去调试,我看到的X,Y,Z设置为1。同样try2值应指向到boh1相关的东西,但调试表明我try2的值为1.000000。那么,什么是实际发生的?

I realize that try points to the first Vec, which is boh1, so if I go debugging, I see the x,y,z values set to 1. Likewise try2 should be pointing to "something" related to boh1, but the debug shows me that try2 has the value 1.000000. So, what is actually happening?

编辑:试一试也不会在C作为一个变量的名字++。

"try" can't be used as name of a variable in c++.

推荐答案

它仍然给你一个指针 VEC ,这是不是一个可言。什么是铸造的作用是告诉编译器完全不顾实际类型的尝试,有效pretending的尝试是什么不是。

It will still give you a pointer to Vec, which is not a double at all. What the casting does is telling the compiler to completely disregard the actual type of try, effectively pretending that try is something it's not.

使用 try2 将导致的未定义行为

这篇关于铸造VEC *为double *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆