首页 > 解决方案 > 在结构中定义常量

问题描述

我正在尝试创建一个包含一些常量的结构,如下所示:

#include <CoreAudio/CoreAudio.h>
...
struct properties {
    //Volume control
    const AudioObjectPropertyAddress volume = {
        kAudioDevicePropertyVolumeScalar, //mSelector
        kAudioDevicePropertyScopeOutput, //mScope
        0 //mElement
    };
    //Mute control
    const AudioObjectPropertyAddress mute = { 
        kAudioDevicePropertyMute,
        kAudioDevicePropertyScopeOutput,
        0
    };
};

但是,我无法访问此类中的常量;

//Function used to for example set volume level or set mute status
//bool setProperty(UInt32 data_to_write, AudioObjectPropertyAddress addr_to_write_to);
//Following line should mute the system audio
setProperty(1, properties::mute);

这将使编译器返回以下错误:

error: invalid use of non-static data member 'mute'

所以,我试着让常量像这样静态:

const static AudioObjectPropertyAddress volume = { ...

但是现在,我得到了一个不同的错误:

error: in-class initializer for static data member of type 'const AudioObjectPropertyAddress' requires 'constexpr' specifier

我尝试的最后一件事是更改const staticstatic constexpr,但是我再次无法访问常量。每次我尝试访问它们时,编译器都会显示此错误:

Undefined symbols for architecture x86_64:
  "properties::mute", referenced from:
      _main in main-fefb9f.o
ld: symbol(s) not found for architecture x86_64

我不太确定这里发生了什么,我尝试将我的结构转换为一个类,但我最终得到了同样的Undefined symbols错误。我知道我可以将这两个常量定义为全局变量,但我认为将它们放入结构/类中会使代码看起来“更好”或者更有条理。有人可以解释一下这里出了什么问题并提供可能的解决方案吗?

标签: c++c++11

解决方案


为什么不只是 properties.volume 和 properties.mute 或使用命名空间,否则......

namespace properties 
{
    //Volume control
    const AudioObjectPropertyAddress volume = {
        kAudioDevicePropertyVolumeScalar, //mSelector
        kAudioDevicePropertyScopeOutput, //mScope
        0 //mElement
    };

    //Mute control
    const AudioObjectPropertyAddress mute = { 
        kAudioDevicePropertyMute,
        kAudioDevicePropertyScopeOutput,
        0
    };
};

推荐阅读