How to solve C syntax error: 'expected unqualified-id before '<' token'?
In the development of C, we often encounter various errors. One of the common errors is 'expected unqualified-id before '<' token'. This error usually means that an identifier is missing somewhere, but the compiler found the '<' symbol. This error is common when using templates or generic programming.
In this article, we will discuss how to identify and resolve this syntax error and provide some examples of common mistakes.
1. Reasons for the error
Usually, the 'expected unqualified-id before '<' token' error is caused by two common problems:
2. Error examples and solutions
template<class T> class MyClass { public: T value; }; int main() { MyClass<int> obj; // 正确用法:给模板传入适当的参数 MyClass obj2; // 错误用法:未给模板传入参数 obj.value = 10; return 0; }
In the above example, in the definition When using the MyClass
class, you need to pass it a template parameter <class T>
. When creating object obj
, we successfully passed an appropriate parameter <int>
to the template. But when creating object obj2
, we did not pass in parameters to the template. In this case, the compiler will report an error and prompt 'expected unqualified-id before '<' token'. To solve this error, we only need to pass in a suitable template parameter to the obj2
object, such as <int>
.
Solution to Example 1:
MyClass<int> obj2; // 给模板传入适当的参数
#include <iostream> int main() { std::cout << "Hello World" << std::endl return 0; }
In the above example, in the output statement std: :cout << "Hello World" << There is no semicolon after std::endl
. In this way, the compiler will prompt the 'expected unqualified-id before '<' token' error. To resolve this error, we simply add a semicolon to the end of the statement.
Example 2 solution:
std::cout << "Hello World" << std::endl; // 添加分号
3. Summary
In the development of C, the 'expected unqualified-id before '<' token' error is a common Grammatical errors. It's usually caused by missing template parameters or missing semicolons. By carefully checking the code and adding appropriate parameters or semicolons where the problem is, we can successfully resolve this error.
The above is the detailed content of How to solve C++ syntax error: 'expected unqualified-id before '<' token'?. For more information, please follow other related articles on the PHP Chinese website!