C++ 声明类的 const 成员对象
c++ declaring a class's const member object
我指的是这个堆栈溢出帖子:
当我构建以下代码时,我得到:"建筑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 文件,而不是标头。在标头中,包含它的每个编译单元都会创建一个新的编译单元,然后链接器理所当然地抱怨重复项。
相关文章:
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何从构造函数副本 T(const T&)调用对象 T?
- 不允许运算符 const 参数调用 const 成员函数
- 在运行时有条件地删除类成员或跳过调用该成员对象的构造函数
- c++ 是否保证标头初始化的静态 const 成员跨编译单元和库共享单个实例?
- C++是否有定义的方法来传递指向类的成员对象的成员函数的指针
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 声明成员对象而不调用其默认构造函数
- 在类声明中初始化 const 成员变量时在调试模式下出现异常
- 将 const 类型引用对象注册为类成员对象C++
- decltype 不会推断 const 对象的 const 成员
- 在对象构造后初始化 const 成员变量
- 构造具有const成员的对象时调用另一个构造函数
- C++ 声明类的 const 成员对象
- 如何赋值具有const成员的数据对象
- 如何复制(或交换)包含引用或const成员的类型的对象
- 设置具有const成员的成员对象
- 我可以有一个返回*this并处理非常量对象的const成员函数吗
- 如何禁止在c++ 2011中调用右值对象的const成员函数?
- 返回带有const getter函数的成员对象,但它是可修改的