错误示范:
#include<iostream>
#include<string>
using namespace std;
class person {
public:
person()
{
}
person(int age)
{
age = age;
}
int age;
};
void test01()
{
person p1(18);
cout << "p1的年龄为:" << p1.age << endl;
}
int main()
{
test01();
}
改正:
#include<iostream>
#include<string>
using namespace std;
class person {
public:
person()
{
}
person(int age)
{
this->age = age;//this指针指向 被调用的成员函数 所属的对象,即p1!!!
}
int age;
};
//解决名称冲突
void test01()
{
person p1(18);
cout << "p1的年龄为:" << p1.age << endl;
}
int main()
{
test01();
}
可正常打印年龄
创建personAddAge()函数进行类加
#include<iostream>
#include<string>
using namespace std;
class person {
public:
person()
{
}
person(int age)
{
this->age = age;
}
void personAddAge(person& p)
{
this->age += p.age;
}
int age;
};
//返回对象本身用*this
void test02()
{
person p1(10);
person p2(10);
p2.personAddAge(p1);
cout << "p2.age: " <<p2.age << endl;
}
int main()
{
test02();
}
返回对象本身用*this:
#include<iostream>
#include<string>
using namespace std;
class person {
public:
person()
{
}
person(int age)
{
this->age = age;
}
//如果你要返回本体,要做一个引用的返回 person&
//如果你要返回一个值的方式返回,一定是创建一个新的对象,
//如果是要一个引用的返回,不会创建新的对象,会一直返回p2
person& personAddAge(person& p)
{
this->age += p.age;
return *this;
}
int age;
};
//返回对象本身用*this
void test02()
{
person p1(10);
person p2(10);
//链式编程
p2.personAddAge(p1).personAddAge(p1).personAddAge(p1);//返回的是p2,重新调用add累加
cout << "p2.age: " <<p2.age << endl;
}
int main()
{
test02();
}