简体   繁体   English

如何转发声明未命名命名空间中的类

[英]How to forward declare class which is in unnamed namespace

I am trying to create class with lazy calculations.我正在尝试使用懒惰的计算创建类。 So I need struct to hold previously calculated variables and I want to put that class into unnamed namespace(don't want to pollute global scope).所以我需要 struct 来保存以前计算的变量,我想将该类放入未命名的命名空间(不想污染全局范围)。 Here is minimal code which explains what I want: calculator.h :这是解释我想要的最小代码: calculator.h

#ifndef CALCULATOR_H
#define CALCULATOR_H

class PrevCalc;
class Calculator
{
public:
    Calculator();
    PrevCalc* prevCalc;
};

#endif // CALCULATOR_H

calculator.cpp : calculator.cpp

#include "calculator.h"
namespace{
    struct PrevCalc{
        double prevA = -1;
        double prevB = -1;
        double prevC = -1;
    };
}
Calculator::Calculator()
{
    prevCalc = new PrevCalc();
}

Of course it gives an error expected type-specifier before 'PrevCalc' and if I define PrevCalc without namespace everything works fine.当然,它expected type-specifier before 'PrevCalc'给出了一个错误的expected type-specifier before 'PrevCalc' ,如果我定义没有命名空间的PrevCalc一切正常。 My question is how to declare class which will be defined in unnamed namespace in .cpp file我的问题是如何声明将在.cpp文件中的未命名命名空间中定义的类

My question is how to declare class which will be defined in unnamed namespace in .cpp file我的问题是如何声明将在.cpp文件中的未命名命名空间中定义的类

You cannot.你不能。 The unnamed namespace is explicitly meant to be privately visible for the current translation unit it appears in, and cannot be used for forward declarations inherently.未命名命名空间明确表示对于它出现在的当前翻译单元是私有可见的,并且本身不能用于前向声明。

You're probably be better off using the pimpl idiom , if you want to hide implementation details.如果您想隐藏实现细节,最好使用pimpl idiom


Another popular approach is using an internal_ namespace, and document it's not meant for public usage:另一种流行的方法是使用internal_命名空间,并记录它不供public使用:

namespace calculators {
namespace internal_ {
    struct PrevCalc{
        double prevA = -1;
        double prevB = -1;
        double prevC = -1;
    };
}

class Calculator {
public:
    Calculator();
private: // !!!!
    internal_::PrevCalc* prevCalc;
};
}

You could also use a nested class ?您还可以使用嵌套类?

#ifndef CALCULATOR_H
#define CALCULATOR_H

class Calculator {
public:
    Calculator();
    ~Calculator(); // need an explicit destructor to use std::unique_ptr<>
private:
    struct PrevCalc;
    std::unique_ptr<PrevCalc> prevCalc;
};

#endif // CALCULATOR_H

in .cc file在 .cc 文件中

#include "calculator.h"

struct Calculator::PrevCalc{
  double prevA = -1;
  double prevB = -1;
  double prevC = -1;
};

Calculator::Calculator():
  prevCalc(std::make_unique<PrevCalc>())
{}

Calculator::~Calculator(){}

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

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