1
#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

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

4

2 回答 2

4

As mentioned above forward declaration only let's you declare pointers or references.

In your example you don't technically need forward declaration because you can just declare the AAH class before the main function.

于 2013-10-28T23:45:47.440 回答
3

You can't use object without it's prototype declared. Forward declaration is good only to let you declare a pointer or reference without include and add lot of dependencies.

In header files you don't want many unnecessary includes. many include can cause long compilation time. therefore when you just need to declare a pointer or a reference, in class or function prototypes, it is good idea to use forward declaration instead of include.

look at the sample:

file A.h

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

file B.h

//fwd declaration instead of include
class A;

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

file B.cpp

#include "B.h"
#include "A.h" //have to include since I using the obj.
B::B(const A& a){
   a.func();
}
于 2013-10-28T23:44:53.630 回答