I want to initialize a private static member variable of private type.
A minimal working example looks like the following.
error.hpp
file
#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
#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. Moving error_desc
to the public
section makes the program to compile fine.
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.
Thank you in advance.
You're trying to define a global variable named desc
(which fails as expected because error::error_desc
is private
).
The correct syntax to define the static
member error::desc
should be
const error::error_desc error::desc{0, "Ok"};
// ^^^^^^^
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.