C++ 当我在两个不同的CPP中访问静态常量成员变量时,得到;“多重定义”;

C++ 当我在两个不同的CPP中访问静态常量成员变量时,得到;“多重定义”;,c++,c++11,stl,C++,C++11,Stl,我有一个非模板类字符串(String.h): 我在不同的cpp文件(string.cpp)中初始化它: 可能是字符串.h的标题有问题。 您可以尝试使用一次#pragma来解决此问题 #pragma once class String { public: static const unsigned int npos; ... }; 请包含错误消息。您可以设置一个复制您的问题的程序吗?您是否有适当的头包含保护?您不需要/应该在测试代码中包含您的实现文件。只需将其链接到测试运行程序。@u

我有一个非模板类字符串(String.h):

我在不同的cpp文件(string.cpp)中初始化它:


可能是字符串.h的标题有问题。 您可以尝试使用一次
#pragma
来解决此问题

#pragma once

class String {
 public:
  static const unsigned int npos;
  ...
};

请包含错误消息。您可以设置一个复制您的问题的程序吗?您是否有适当的头包含保护?您不需要/应该在测试代码中包含您的实现文件。只需将其链接到测试运行程序。@user0042如果这是模板实现,则不需要。但是OP说变量是在.cpp文件中定义的。@Swift如果它是一个模板定义,那么模板定义代码是否应该包含在标题中?
const unsigned int String::npos = static_cast<unsigned int>(-1);
template<typename _CharT, typename _Traits, typename _Alloc>
class basic_string
{
public:
  ...
  ///  Value returned by various member functions when they fail.
  static const size_type    npos = static_cast<size_type>(-1);
  ...
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION

#if _GLIBCXX_USE_CXX11_ABI

  template<typename _CharT, typename _Traits, typename _Alloc>
    const typename basic_string<_CharT, _Traits, _Alloc>::size_type
    basic_string<_CharT, _Traits, _Alloc>::npos;
  ...
#include "string-def.h"
#include "string-impl.h"

#include <gtest/gtest.h>

TEST(IndexOfTest, CharTest) {
  String str = "123456";
  EXPECT_EQ(str.IndexOf('0'), String::npos);
}
#include "string-def.h"
#include "string-impl.h"

#include <gtest/gtest.h>

TEST(IndexOfTest, CharTest) {
  String str = "123456";
  EXPECT_EQ(str.IndexOf("000"), String::npos);
}
CMakeFiles\tests.dir/objects.a(string-indexof-char-test.cc.obj):string-indexof-char-test.cc:(.rdata+0x640): 
multiple definition of `citron::String::npos'
CMakeFiles\tests.dir/objects.a(string-indexof-sequence-test.cc.obj):string-indexof-sequence-test.cc:(.rdata+0x230): first defined here
collect2.exe: error: ld returned 1 exit status
#pragma once

class String {
 public:
  static const unsigned int npos;
  ...
};