简体   繁体   English

建议使用C ++的“const”关键字

[英]Advice for using “const” keyword of C++

I am writing classes for Vector3 and Quaternion. 我正在为Vector3和Quaternion编写课程。 Here is my code: 这是我的代码:

// .h file
Quaternion operator * (const Vector3& v) const;

// .cpp file
Quaternion Quaternion::operator * (const Vector3& v) const
{
    float s = -(m_v.dot(v));
    Vector3 vt = (v*m_s) + m_v.cross(v);
    return Quaternion(s, vt.getX(), vt.getY(), vt.getZ());
}

I got errors with "return" line because I declared inside Vector3.h like this: 我在“返回”行中出错,因为我在Vector3.h中声明如下:

float&  getX();
float&  getY();
float&  getZ();

I figured out I could pass this case by declaring like here: 我想通过这样声明我可以通过这个案例:

const float&    getX() const;
const float&    getY() const;
const float&    getZ() const;

I also saw I would not use this anymore: 我也看到我不再使用它了:

Vector3 v(1.0f, 2.0f, 3.0f);
v.getX()++;
// or v.getX() += 1; => coz I feel writing code like this is more readable.

And must write code like this: 并且必须编写如下代码:

float x = v.getX();  // I dont like this coz it will waste memory
                     // if it's not an "float" but a big object
x += 1;
v.setX(x);

So, my questions: 所以,我的问题:

  1. Is there any way to satisfy both of these cases, or it,simply, is a trade-off of choise? 有没有办法满足这两种情况,或者简单地说,它是一种权衡取舍?
  2. Is it a good practice for C++ programmer to use "const" keyword often? C ++程序员经常使用“const”关键字是一个好习惯吗?

What you can do is provide two different versions of the function. 您可以做的是提供两种不同版本的功能。

class Vector {
    public:
        float getX() const;
        float & getX();
};

void foo(const Vector & const_v, Vector & v) {
    v.getX() += 1;
    const_v.getX() += 1; // Won't work.
}

Note that if your Vector is simply a container for data, it is more simple to just declare it a struct and allow direct access to all members. 请注意,如果您的Vector只是数据的容器,则将其声明为struct并允许直接访问所有成员更为简单。 You should use getters and setters only when there is a non-zero chance that access to private fields should be regulated somehow (for example, you want that a Vector is constantly normalized so any writing to a field should alter all of them in a very specific way). 只有当存在以某种方式调节对私有字段的访问的非零概率时才应该使用getter和setter(例如,你希望Vector被不断规范化,因此任何对字段的写入都应该改变它们中的所有字段。具体方式)。

First of all, in the general case, you should mark everything as const if possible. 首先,在一般情况下,如果可能,您应该将所有内容标记为const Doing so can save you a lot of debugging or documentation reading later on, because the compiler can help diagnosing logical problems. 这样做可以节省大量的调试或文档读取,因为编译器可以帮助诊断逻辑问题。

For returning references to private members, the C++ standard library uses the approach of having two duplicate versions, one declared const and the other not. 对于返回对私有成员的引用,C ++标准库使用具有两个重复版本的方法,一个声明为const而另一个不是。 This can be your approach as well. 这也可以是你的方法。

But in your specific case you can just make these public. 但在您的具体情况下,您可以公开这些。 A lot of books tell you to always declare members as private and use getters and setters because that is how "OOP works", but it is not true. 很多书告诉你总是将成员声明为私有并使用getter和setter,因为这就是“OOP的工作原理”,但事实并非如此。 If a class simply holds data and provides no other abstraction, then there is nothing to gain by making these fields private. 如果一个类只是保存数据而不提供其他抽象,那么将这些字段设为私有就没有任何好处。

Lastly, if you are super concerned about efficiency, you should return a float whenever you don't actually need a float& . 最后,如果你是超级关心效率,你应该返回一个float时,你实际上并不需要一个float& The latter also requires memory or register allocation, possibly larger than the memory taken by a plain float . 后者还需要内存或寄存器分配,可能大于普通float所占用的内存。 Accessing a float& also requires indirection, which is rather costly. 访问float&并且还需要间接,这是相当昂贵的。

在get函数中使用const是一种很好的编程习惯,因为get函数应该只具有读取数据的权限,而不是修改数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM