c++ - 在结构中定义常量
问题描述
我正在尝试创建一个包含一些常量的结构,如下所示:
#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 static
为static 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
错误。我知道我可以将这两个常量定义为全局变量,但我认为将它们放入结构/类中会使代码看起来“更好”或者更有条理。有人可以解释一下这里出了什么问题并提供可能的解决方案吗?
解决方案
为什么不只是 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
};
};
推荐阅读
- elasticsearch - 如何分离 Elastic APM 代理?
- angular - 如何在firebase实时数据库中设置数据值?
- c# - 如何使用社交分享插件向 whatsapp 群组发送短信
- python - 使用 PyQt 的 QLineEdit 滚动条
- google-cloud-dataflow - 为什么 mongoio Reshuffle 不能在数据流上工作
- python - 从 RESTAPI url 在 python 中下载大型 zip 文件只会下载 1KB 的文件
- c# - 如何使用 MongoDB 驱动程序在 mongodb 中“选择 WHERE”
- python - 变量在 def 函数 python 3.4.0 内重置
- javascript - 一次显示多个数据点:Highcharts
- python - CVXOPT QP SOLVER : TypeError: 'A' must be a 'd' matrix with 10 columns