gpt4 book ai didi

c++ - 为什么这个函数没有被编译器捕获,它做了什么?

转载 作者:行者123 更新时间:2023-11-27 22:30:14 25 4
gpt4 key购买 nike

我在一些遗留代码中发现我正在处理这个函数(在 C++ 中)

Vec3d Minimum()
{
if(this->valid)
{
return minBB;
}
else
{
return NULL;
}
}

其中 Vec3d 是一个对象,它基本上是一个具有 x、y、z 和一些运算符重载的结构(下面的代码)。

据我所知,您不能为用户定义的对象返回 0...或者是否有一些我不知道的自动转换为零?这只是出于好奇:p

谢谢

class Vec3d
{
public:
double x,y,z;

/// \brief Default constructor initializes x and y to 0
Vec3d();

/** \brief Constructor initializies vector to input parameters x and y and z
*
* \param x Double value that initializes x value of vector
* \param y Double value that initializes y value of vector
* \param z Double value that initializes z value of vector
*/
Vec3d(double x, double y, double z);

/** \brief Copy constructor
*
* \param v Pointer to another vec3i with which to initialize current vec3i
*/
Vec3d(Vec3d* v);

/**\brief Sets a vector (already instantiated) to the input parameters (x,y,z)
*
* \param x Double value that initializes x value of vector
* \param y Double value that initializes y value of vector
* \param z Double value that initializes z value of vector
*
* This method is just so you can change the value of an already instantiated vector
*/
void set(double xi, double yi, double zi);

const Vec3d operator -(const Vec3d &other) const;
const Vec3d operator +(const Vec3d &other) const;
const Vec3d operator *(const double num) const;
const double operator *(const Vec3d &other) const;
const Vec3d operator /(const double num) const;
double magnitude();
};

最佳答案

0 可以在指针上下文中用作空指针常量。也就是说,它会进入这里:

Vec3d(Vec3d* v); 

请注意注释不正确,因为它不是复制构造函数。

代码有点粗制滥造。不需要 set 函数,通常非变异运算符应该是自由函数。尤其重要的是,拥有像它这样的构造函数是一种浪费和困惑。如果你有一个指向 vector 的指针,你应该这样做:

Vec3d v = *other;

不提供从指针的隐式转换。

关于c++ - 为什么这个函数没有被编译器捕获,它做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3489774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com