C ++静态const结构初始化

时间:2018-12-27 05:52:20

标签: c++

我有一个基于按钮输入来更改颜色的类。我想预定义一堆“颜色”,以便状态机可以简单地将标头中定义的常量结构复制到某个变量以更改颜色。

我不明白为什么使用以下代码会使编译器过于笨拙,但链接程序无法对其进行处理。有没有更好的模式来定义常量结构?我应该让它们成为非静态非const并与之一起生活吗?

class ColorManager {
 public:

  ColorManager () {
  }

  // ProcessButton uses the static constexpr structs defined below
  void ProcessButton(uint8_t button_state);

 private:
  // Color_t is defined elsewhere as a struct of R, G, B fields
  static constexpr Color_t kColorWhite  = {100, 100, 100};
  static constexpr Color_t kColorRed    = {100, 0, 0};
  static constexpr Color_t kColorPurple = {100, 0, 70};

};

编辑: 这是示例错误消息:

src/color_manager.o: In function `ColorManager::ProcessButton(uint8_t button_state)':
color_manager.cc:(.text+0x224): undefined reference to `ColorManager::kColorWhite'
collect2: error: ld returned 1 exit status

1 个答案:

答案 0 :(得分:2)

在C ++ 17之前,这些constructor(props: any) { super(props); this.state = { onEdit: false, } this.onBlur = this.onBlur.bind(this); this.onEndEditing = this.onEndEditing.bind(this); } private onBlur() { this.setState({ onEdit: true }); } private onEndEditing() { this.setState({ onEdit: !this.state.onEdit }); } private get searchView() { const { onEdit } = this.state; return ( <View style={styles.searchContainer}> <View style= {[styles.search, onEdit === true || this.props.keyword.length !== 0 ? undefined : { justifyContent: 'center' }]}> <Image source={searchIcon} style={[styles.image, { marginLeft: onEdit === true || this.props.keyword.length !== 0 ? 10 : 0 }]} /> <TextInput style={styles.searchInput} placeholder={'search'} onEndEditing={this.onEndEditing} onFocus={this.onBlur} defaultValue={this.props.keyword} clearButtonMode="while-editing" /> </View> </View> ); } const styles = StyleSheet.create({ searchContainer: { height: 72, padding: 16, }, search: { flex: 1, flexDirection: 'row', alignItems: 'center', height: 40, }, image: { marginRight: 10, alignSelf: 'center' }, searchInput: { paddingRight: 10, fontSize: 14, }, }) 静态成员声明不是定义。您需要以某种翻译单位提供定义。

constexpr

在C ++ 17中,这些将是隐式内联变量。