笔者今天写了一个代码
定义了一个person类,里面有一个显示方法,用于显示姓名和年龄
#include<iostream>
#include<cstring>
using namespace std;
class Person
{
public:
Person(string n, int age);
void show_person();
private:
string name;
int age;
};
Person::Person(string n, int age)
{
name=n;
age=age;
}
void Person::show_person()
{
cout<<name<<" "<<age<<endl;
}
int main()
{
Person p1("xiaoli",25);
p1.show_person();
}
但是它显示出来的和预期不一样,年龄显示错误。
后来我在构造函数里面加了this指针,年龄就显示正常了。
有知道原理的朋友可以在评论区指点一下!!!