编译器错误 C2143

语法错误:“token2”的前面缺少“token1”

编译器原本需要特定令牌(即空格以外的语言元素),而找到的是另一个令牌。

查看 C++ 语言参考以确定代码在语法上不正确的位置。 由于编译器可能会在遇到导致问题的行后报告此错误,因此请检查错误前面的几行代码。

C2143 可能在不同的情况下发生。

可限定名称(::->.)的运算符后面必须跟有关键字 template 时可能发生,如下例所示:

class MyClass
{
    template<class Ty, typename PropTy>
    struct PutFuncType : public Ty::PutFuncType<Ty, PropTy> // error C2143
    {
    };
};

默认情况下,C++ 会假定 Ty::PutFuncType 不是模板;因此,后面的 < 解释为小于号。 必须显式告知编译器 PutFuncType 是模板,以便其正确分析尖括号。 若要更正此错误,请在依赖类型的名称上使用 template 关键字,如下所示:

class MyClass
{
    template<class Ty, typename PropTy>
    struct PutFuncType : public Ty::template PutFuncType<Ty, PropTy> // correct
    {
    };
};

在使用 /clr 并且 using 指令有语法错误时,可能发生 C2143

// C2143a.cpp
// compile with: /clr /c
using namespace System.Reflection;   // C2143
using namespace System::Reflection;

在通过使用 CLR 语法而不使用 /clr 尝试编译源代码文件时,它也可能发生

// C2143b.cpp
ref struct A {   // C2143 error compile with /clr
   void Test() {}
};

int main() {
   A a;
   a.Test();
}

跟在 if 语句后的第一个非空白字符必须是左括号。 编译器无法转换任何其他内容:

// C2143c.cpp
int main() {
   int j = 0;

   // OK
   if (j < 25)
      ;

   if (j < 25)   // C2143
}

在检测到错误的行上或紧靠该行的上面某行中缺少右大括号、圆括号或分号时,可能发生 C2143:

// C2143d.cpp
// compile with: /c
class X {
   int member1;
   int member2   // C2143
} x;

或者类声明中存在无效的标记时:

// C2143e.cpp
class X {
   int member;
} x;

class + {};   // C2143 + is an invalid tag name
class ValidName {};   // OK

或者一个标签未附加到语句时。 如果必须单独放置标签,例如在复合语句的末尾处,请将它附加到 null 语句:

// C2143f.cpp
// compile with: /c
void func1() {
   // OK
   end1:
      ;

   end2:   // C2143
}

当对 C++ 标准库中的类型进行非限定调用时,该错误也可能发生:

// C2143g.cpp
// compile with: /EHsc /c
#include <vector>
static vector<char> bad;   // C2143
static std::vector<char> good;   // OK

或者缺失 typename 关键字:

// C2143h.cpp
template <typename T>
struct X {
   struct Y {
      int i;
   };
   Y memFunc();
};
template <typename T>
X<T>::Y X<T>::memFunc() {   // C2143
// try the following line instead
// typename X<T>::Y X<T>::memFunc() {
   return Y();
}

或者尝试定义显式实例化:

// C2143i.cpp
// compile with: /EHsc /c
// template definition
template <class T>
void PrintType(T i, T j) {}

template void PrintType(float i, float j){}   // C2143
template void PrintType(float i, float j);   // OK

在 C 程序中,变量必须在函数的开头声明,不能在函数执行非声明指令后进行声明。

// C2143j.c
int main()
{
    int i = 0;
    i++;
    int j = 0; // C2143
}