这里非常具体的问题!
我有一个类,其中包含有关行星的数据。例如,它有一个向量 (double x, double y, double z) 来保存它的位置,还有一个 double 变量来保存它的半径。
我经常使用引用来获得对私有变量的“只读公共访问”。我调用 setter 方法来更改私有变量。
但是,我认为在向量或列表等动态容器中不允许这样做。
我已经尝试过“常量常量”指针,一旦在初始化列表中初始化了这个想法,它们将无法指向其他任何东西或修改变量。但同样的错误信息出现在编译时。
消息是这样的:“错误:非静态 const 成员const double* const x
,不能使用默认赋值运算符”
因此,当我对向量执行“push_back”时,复制类会出现问题 - 对吧?
这是一个示例代码:
class planet{
private:
double _radius;
public:
// Constructor
planet() : rad(_radius){
_radius = 0.0f;
}
// This is a setter method - works fine
void setrad(double new_rad){
_radius = rad;
}
// This is a better solution to the getter method
// - does not seem to work with dynamic containers!
const double& rad; // This is initialized in the constructor list
};
int main(...){
...
std::vector<planet> the_planets;
planet next_planet_to_push;
next_planet_to_push.setrad(1.0f);
// This causes the error!
the_planets.push_back(next_planet_to_add);
...
}