繁体   English   中英

命名空间中的类正向声明

[英]class forward declaration in a namespace

#include <iostream>
#include <string>
#include <vector>

using std::string;
using std::vector;
using std::endl;
using std::cout;

namespace AAH 
{
    class messageTemplate;
};

using namespace AAH;

int main()
{
    messageTemplate templateMSG32("hello world");
    cout << templateMSG32.version << endl;
    return EXIT_SUCCESS;
}

namespace AAH {    
    class messageTemplate 
    {
    public:
        messageTemplate() : version("XX.XX.XX.001") {}
        messageTemplate(string ver) : version(ver) {}
        string version;
    };
};

好的,这是代码,

我收到一条错误消息:

Error 3 error C2228: left of '.version' must have class/struct/union

我正在使用visual studio 2012

谁能告诉我为什么我得到这个错误

如上所述,前向声明仅允许您声明指针或引用。

在您的示例中,从技术上讲,您不需要前向声明,因为您可以在主函数之前声明AAH类。

如果没有声明原型,就不能使用对象。 前向声明只允许您声明一个指针或引用而没有包含并添加很多依赖项是好的。

在头文件中,您不需要许多不必要的包含。 许多包含可能导致较长的编译时间。 因此,当您只需要在类或函数原型中声明指针或引用时,最好使用正向声明而不是include。

看一下样本:

文件啊

class A{
public:
    void func() const;
};

文件Bh

//fwd declaration instead of include
class A;

class B{
public:
  //use fwd decl.
  B(const A& a);
};

文件B.cpp

#include "B.h"
#include "A.h" //have to include since I using the obj.
B::B(const A& a){
   a.func();
}

暂无
暂无

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

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