简体   繁体   English

C ++错误:不是成员或多重定义

[英]C++ error: not a member OR multiple definition

I am trying to use a static const field which I define inside a class. 我试图使用我在类中定义的静态const字段。
When I define it like that: 当我这样定义时:

class DisjunctionQuery : public Query
{

  public:
    DisjunctionQuery ();
    static const std::string prefix;


};
const std::string DisjunctionQuery::prefix = "Or";

It says: multiple definition of 'DisjunctionQuery::prefix' and if I change it that way (remove the two lines): 它说:'DisjunctionQuery :: prefix'的多重定义,如果我改变它(删除两行):

class DisjunctionQuery : public Query
{

  public:
    DisjunctionQuery ();
    //static const std::string prefix;


};
//const std::string DisjunctionQuery::prefix = "Or";

It says when I try to call it in another place 'prefix' is not a member of 'DisjunctionQuery'. 它说当我尝试在另一个地方调用它时,'prefix'不是'DisjunctionQuery'的成员。

How can I make it work? 我怎样才能使它工作? thanks. 谢谢。

You move the definition to a single implementation file. 您将定义移动到单个实现文件。

If you keep it in the header, you'll break the one definition rule . 如果将其保留在标题中,则会破坏一个定义规则 Each file that includes the header will attempt to define the static member, which is wrong. 包含标头的每个文件都将尝试定义static成员,这是错误的。

//DisjunctionQuery.h
class DisjunctionQuery : public Query
{
  public:
    //....
    static const std::string prefix;
};

//DisjunctionQuery.cpp
#include "DisjunctionQuery.h"
const std::string DisjunctionQuery::prefix = "Or";

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

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