c++ - Const 正确性和运算符 *

标签 c++ constants

我定义了这样一个类:

Quaternion& conjugate();        //negates the vector component of the quaternion
Quaternion  conjugate() const;  //same but in without modifying the class...

Quaternion& operator =  (Quaternion const& Qrhs);
Quaternion& operator *= (Quaternion const& Q);
Quaternion  operator  *  (Quaternion const& Qrhs) const;

现在我像这样使用这个函数:

PRINTVAR(*this);                //this is the first time printed (a little macro to print line and file)
Quaternion vQ(0.,vn), resQ;
resQ = vQ*(this->conjugate());  //this is the method I want to discuss...
PRINTVAR(*this);                //this is the second time
resQ = *this * resQ;

这是输出

*this: (0:0:0:0) at line: 128 in file: Quaternions.cpp
*this: (-0:-0:-0:0) at line: 131 in file: Quaternions.cpp

我认为通过在行 resQ = vQ*(this should be called as const)... 中调用运算符 * 为什么我再次打印 *this 会改变?

这里是共轭函数的定义:

Quaternion& Quaternion::conjugate(){
/* Given:  Nothing
 * Task:   Invert sign of the vector
 * Return: the class which will be modified
*/
    V3 vec;
    vec = -(this->getVector());
    x() = vec[0];
    y() = vec[1];
    z() = vec[2];
    return *this;
}

Quaternion Quaternion::conjugate() const{
    Quaternion result(*this);
    result.conjugate();
    return result;
}

最佳答案

如果您显示的代码是在非常量方法中,那么 this指针是非常量,非常量 conjugate method 当然比 const 更好。重载决策中不考虑返回类型。如果想坚持使用const版本,可以加上constness: resQ = vQ*(static_cast<const Quaternion*>(this)->conjugate());

关于c++ - Const 正确性和运算符 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945560/

相关文章:

c++ - 从 native C++ 代码调用 C++CX

c# - 如何在 C# 中拥有抽象和覆盖常量?

c - 如何在 C 中为 __func__ 赋值?

c++ - 合并两个已排序的 vector

c++ - 在给定的迭代次数之后,使用RAII重新分配资源

java - 在 Java 中 : do expressions involving constants defined at instantiation get simplified during compile-time?

带有 typedef 函数指针的 const 限定符

c++ - 使用 const int 作为数组大小

c++ - .h 文件应该是与外部函数的接口(interface);如何在包含标题的.cc 文件中定义?

c++ - 为什么可以从另一个 unique_ptr get() 创建 unique_ptr 而不会导致错误?