我正在尝试完成一件非常简单的事情:在创建类的实例时,即在调用构造函数时,应初始化类的 protected 常量成员(获取值)。像这样:
MyClass.hpp:
class MyClass {
public:
//some methods
MyClass(){} //Constructor
protected:
const int Variable;
};
MyClass.cpp:
//some method definitions
MyClass::MyClass(int newVariable): Variable(newVariable) {} //constructor
我已经尝试过 static
关键字和其他东西,每个都或多或少地给出了自己的编译器错误。在示例中,“复制赋值运算符被隐式删除”。
这非常令人沮丧,因为在我开始保护成员之前一切正常。
附带说明:如果 const
成员一旦定义就不能修改,是否仍然需要保护和编写 getter/setter 方法?它确实没有加快开发速度......
编辑:相关代码:
#ifndef Servo_hpp
#define Servo_hpp
#pragma once
class Servo{
friend class Grid;
public:
Servo(int newID, int newRow, int newCol);
//Some other methods
const int row;
const int column;
const int number;
double currentAngle;
double nextAngle;
double currentSpeed;
const int ID; //TODO: Change to new grid
};
#endif /* Servo_hpp */
Servo::Servo (int newID, int newRow, int newCol): ID(newID), column(newCol), row(newRow), currentAngle(0), currentSpeed(0), number(0){}
最后一部分在.cpp文件中
编辑2
当我尝试创建 MyClass 的 vector 数组时出现问题:
std::vector<MyClass> MyClassArray;
for (int Variable = 0; Variable < 5; Variable++) {
MyClassArray.push_back(*new MyClass(Variable));
}
}
当我将这段代码与上面的类定义放在一起时,这很好地符合 g++,但 XCode 给出错误“无法分配类型为‘MyClass’的对象,因为它的复制赋值运算符被隐式删除”。我能理解这个问题:不能分配 const 成员,但我不会在任何地方复制 MyClass,是吗?
最佳答案
In the example the "copy assignment operator is implicitly deleted".
这很有道理。赋值是一种变异操作,const
对象(您的数据成员)应该发生变异。您已将类(class)设计为不可分配。
请注意,protected
与此处无关。
注意2:如果你希望能够默认构造你的类,你需要在默认构造函数中初始化它的数据成员:
MyClass(): Variable(42) {}
关于c++ - 在类构造函数中初始化 protected 常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36426635/