美好的一天!请帮我解决我的代码,我尝试使用const指针指向非常量的constexpr类,并在将来更改非常量变量,我的编译器说
"error: ‘Actuator{const Pin{1ul, 1ul}, const Pin{1ul, 2ul}, const Pin{1ul, 3ul}, ((velocity_type*)(& velocity))}’ is not a constant expression"
,
对象act1总是生命,因为它的代码为ARM嵌入式设备
代码:
#include <cstddef>
typedef std::size_t port_type;
typedef std::size_t pin_type;
typedef std::size_t velocity_type;
class Pin {
private:
port_type const _port;
pin_type const _pin;
public:
constexpr Pin(port_type const port, pin_type const pin) :
_port { port }, _pin { pin } {
}
};
class Actuator {
private:
Pin const _enable_pin;
Pin const _dir_pin;
Pin const _step_pin;
velocity_type* const _velocity; //constant pointer to non-constant variable
public:
constexpr Actuator(Pin const ep, Pin const dp, Pin const sp, const velocity_type velocity) :
_enable_pin { ep }, _dir_pin { dp }, _step_pin { sp }, _velocity(const_cast<velocity_type*>(&velocity)) {
}
void set_velocity(const velocity_type velocity) const {*_velocity = velocity;} //try to change velocity
};
int main() {
constexpr Actuator act1 ( Pin { 1, 1 }, Pin { 1, 2 }, Pin { 1, 3 }, 1u );
act1.set_velocity(1u);
}
答案 0 :(得分:1)
根据c ++标准[expr-const]/2(强调我的)
表达式e是核心常量表达式,除非评估 e,遵循抽象机器的规则,将评估其中一个 以下表达式:
(...)
15. reinterpret_cast
((velocity_type*)(& velocity))
绝对是一种重新诠释的形式,所以它不能用于常量表达......