我正在尝试用 C++ 构建一个颜色类,
这不是作业,只是我仍在为引用和常量而苦苦挣扎。
--颜色.h
class Color{
private:
double r;
double g;
double b;
double a;
public:
//constructor, getters and setters...
Color& operator =(Color& other_color); //(1)
}
--颜色.cpp
Color& operator=(Color& other_color){
this->r = other_color.get_r(); //line 41
this->b = other_color.get_b();
//and so on...
return *this;
}
像这样它工作正常但我听说必须放置一个 const 以避免错误地通过赋值操作修改对象,因此必须将另一个对象声明为 const。像这样:
Color& operator =(Color const& other_color); //(2)
但它给了我这个错误:
/Users/../color.cpp:41: error: passing 'const Color' as 'this' argument of 'float Color::get_r()' discards qualifiers
所以这是我的问题......
这里发生了什么?其次,如果我不将 other_color 声明为 const 会怎样?可能的错误是什么?
PS.: 小红包问题:
我想将我的变量传递给 opengl glColor4v(colorx.return_rgba()) 返回类 Color 的数组 [r,g,b,a]。这:
float* Color::return_rgba(){
float rgba[4] = {this->r, this->g, this->b, this->a};
return rgba;
}
不会工作,因为返回后 rgba 将不再在范围内,所以它将被删除,我的指针将指向未初始化的地址,该死的......
最佳答案
passing 'const Color' as 'this' argument of 'float Color::get_r()' discards qualifiers
这意味着您必须更进一步。 get_r
可能声明为
float get_r()
并使其工作(const-correctly),你应该做到
float get_r() const
second what would happen if I don't declare other_color as const?
您将无法从 const
限定的 Color
中赋值。您通常希望能够使用 const
对象作为赋值源。此外,它让代码的读者清楚地知道不修改源代码的意图。
I want to pass my variable to the opengl glColor4v(colorx.return_rgba()) returning the array [r,g,b,a] of the class Color.
返回一个包含数组并自动转换为float*
的特殊“车辆”。有事
struct ColorQuadruplet
{
float data_[4];
// add initialization and such here
operator float*() { return data_; }
};
ColorQuadruplet Color::get_rgba() const
{
ColorQuadruplet ret;
// fill ret
return ret;
}
关于c++ - 运算符重载 = 和 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829495/