How to solve C syntax error: 'expected primary-expression before '.' token'?
When writing programs in C, we sometimes encounter various syntax errors. One of the common errors is 'expected primary-expression before '.' token'. When we use incorrect syntax to access members of a class in our code, the compiler will report this error.
This error is usually caused by the following reasons:
Here are some sample codes to illustrate how to solve this error:
Example 1:
#include <iostream> using namespace std; int main() { int length = 10; cout.length; // 错误:应该使用点运算符来访问一个类对象的成员 return 0; }
Fix: Change cout.length to cout< Example 2: Fixation method: Modify myObject.printHello() to myObject->printHello(). Example 3: Repair method: Modify MyObject.printHello() to myObject.printHello(). Through the above repair methods, we can solve the 'expected primary-expression before '.' token' error. It should be noted that the solution to this error is to fix it according to the specific code situation and ensure that the correct syntax is used to access the members of the class. At the same time, when writing code, we must also carefully check and review the code to avoid such common grammatical errors to improve the quality and stability of the program. To summarize, the 'expected primary-expression before '.' token' error is caused by using incorrect syntax when accessing members of the class. We can easily resolve this error by declaring and defining class objects using the correct use of dot and arrow operators. When we encounter such errors, we can carefully check the code and make repairs according to the specific situation to ensure the normal operation of the program. The above is the detailed content of How to solve C++ syntax error: 'expected primary-expression before '.' token'?. For more information, please follow other related articles on the PHP Chinese website!#include <iostream>
using namespace std;
class MyClass {
public:
void printHello() {
cout<<"Hello"<<endl;
}
};
int main() {
MyClass* myObject;
myObject.printHello(); // 错误:应该使用箭头运算符来访问指针对象的成员
return 0;
}
#include <iostream>
using namespace std;
class MyClass {
public:
void printHello() {
cout<<"Hello"<<endl;
}
};
int main() {
MyClass myObject;
MyObject.printHello(); // 错误:使用了未定义的对象
return 0;
}