[英]Why undeclared identifier error occurres while I'm using objet in class's function?
I've been self teaching CPP OOP and this error occurred: Error C2065 'carObj1': undeclared identifier我一直在自学 CPP OOP 并且发生了这个错误: Error C2065 'carObj1': undeclared identifier
And since I'm self teaching I tried to search on Inte.net but nothing found?由于我是自学,所以我尝试在 Inte.net 上搜索但没有找到任何结果? Can anyone help me with this?谁能帮我这个?
#include <iostream>
#include <string>
using namespace std;
class car {
public:
string brand;
string model;
int year;
void enterCar() {
cout << "\nYour car is:" << carObj1.brand << " MODEL:" << carObj1.model << " BUILT-IN:" << carObj1.year;
}
};
int main()
{
car carObj1;
cout << "Enter your car's brand name:\n";
cin >> carObj1.brand;
cout << "Enter your car's Model:\n";
cin >> carObj1.model;
cout << "Enter your car's Built-in year:\n";
cin >> carObj1.year;
carObj1.enterCar();
return 0;
}
The problem is that you're trying to access the fields brand
, model
and year
on an object named carObj1
which isn't there in the context of the member function car::enterObj
.问题是您正在尝试在名为carObj1
的 object 上访问字段brand
、 model
和year
,这在成员 function car::enterObj
的上下文中不存在。
To solve this you can either remove the name carObj1
so that the implicit this
pointer can be used or you can explicitly use the this
pointer as shown below:要解决此问题,您可以删除名称carObj1
以便可以使用隐式this
指针,或者您可以显式使用this
指针,如下所示:
void enterCar() {
//-------------------------------------------vvvvv-------------->equivalent to writing `this->brand`
std::cout << "\nYour car is:" << brand <<std::endl;
//-----------------------------------vvvvvv------------------->explicitly use this pointer
std::cout<< " MODEL:" << this->model << std::endl;
std::cout<<" BUILT-IN:" << this->year;
}
Also i would recommend learning C++ using a good C++ book .我还建议使用一本很好的 C++ 书来学习 C++。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.