简体   繁体   English

私有类型的静态const成员

[英]Static const member of private type

I want to initialize a private static member variable of private type. 我想初始化一个私有类型的私有静态成员变量。

A minimal working example looks like the following. 一个最小的工作示例如下所示。

error.hpp file error.hpp文件

#pragma once

class error {
 public:
  error();
  ~error();

 private:
  struct error_desc {
    int code;
    const char *desc;
    error_desc(int c, const char *d) : code{c}, desc{d} {}
  };

  static const error_desc desc;
};

error.cpp file error.cpp文件

#include "pch.h"
#include "error.h"

const error::error_desc desc{0, "Ok"};

error::error() {}

error::~error() {}

Obviously, this results in an error since error::error_desc type is private. 显然,这会导致错误,因为error::error_desc类型是私有的。 Moving error_desc to the public section makes the program to compile fine. error_desc移到public部分可以使程序编译良好。

Is there any other way to solve this issue still keeping the type private. 还有其他方法可以解决此问题,但仍将类型保留为私有。 The only workaround I can think of is to enclose error::error_desc in a detail namespace and use it in the error class (which of course is not ideal), but I would really like to know a proper solution to this problem. 我能想到的唯一解决方法是将error::error_desc放在detail名称空间中,并在error类中使用它(当然这不是理想的选择),但是我真的很想知道该问题的正确解决方案。

Thank you in advance. 先感谢您。

You're trying to define a global variable named desc (which fails as expected because error::error_desc is private ). 您正在尝试定义一个名为desc的全局变量(由于error::error_descprivate ,所以预期失败)。

The correct syntax to define the static member error::desc should be 定义static成员error::desc的正确语法应为

const error::error_desc error::desc{0, "Ok"};
//                      ^^^^^^^

LIVE 生活

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM