C++ 声明类的 const 成员对象

c++ declaring a class's const member object

本文关键字:const 成员对象 声明 C++      更新时间:2023-10-16

我指的是这个堆栈溢出帖子:

当我构建以下代码时,我得到:"建筑x86_64的重复符号"。在过去的几个小时里,我一直在谷歌上搜索,但没有找到任何帮助。有什么建议吗?

#ifndef __lexer__lexer__
#define __lexer__lexer__
#include <stdio.h>
#include <string>
namespace Tag{
  const int AND = -1,
  OR = -2;
}
class Token{
public:
  std::string Name;
  std::string Type;
  std::string Value;
  int Tag;
  Token(std::string name, std::string type, std::string value, int tag){
    Name = name;
    Type = type;
    Value = value;
    Tag = tag;
  }
};
class Word : public Token{
public:
  Word(std::string name, std::string type, std::string value, int tag) : Token(name, type, value, tag){}
  static const Word AND;
};
const Word Word::AND = *new Word("and", "logical", "&&", Tag::AND);
#endif /* defined(__lexer__lexer__) */

代码:

const Word Word::AND = *new Word("and", "logical", "&&", Tag::AND);

是什么给了我问题。

简短的回答是你不想在.h文件中做定义(而不是声明)。当 .h 文件包含在多个其他文件中时,会出现错误。

稍长的答案是,您的*new习语是不必要的,并且可能会浪费少量存储空间。

const Word Word::AND("and", "logical", "&&", Tag::AND);

将调用相同的构造函数。

一个更长的答案是 Tag 应该是一个枚举,你不想按值传递 std::string。也许你来自另一种语言:你需要学习通过引用和常量引用传递。

初始化代码属于 .cc 文件,而不是标头。在标头中,包含它的每个编译单元都会创建一个新的编译单元,然后链接器理所当然地抱怨重复项。