gpt4 book ai didi

C++声明一个类的常量成员对象

转载 作者:太空宇宙 更新时间:2023-11-04 15:38:53 25 4
gpt4 key购买 nike

我指的是这个 stackoverflow post :

当我构建以下代码时,我得到:“体系结构 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。也许您来自另一种语言:您需要了解按引用传递和常量引用。

关于C++声明一个类的常量成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com