&引用类型
C语言:
int a = 10;
int* b = &a;
*b = 20; //此时 a 的值变成了20
函数传递:
void modify(int* p)
{
*p = 100;
}
int main()
{
int x = 10;
modify(&x); // 必须要取地址
}
C++:
int a = 10;
int *b = &a;
int& ref = a; //ref是a的别名
ref = 20; //ref和a都是20
int a = 10;
int& ref = a;
cout << a; // 10
cout << ref; // 10
ref = 99;
count << a; // 99
函数传递:
void modify(int& ref)
{
ref = 100;
}
int main()
{
int x = 10;
modify(x); // 不需要&,直接传
}
class Builder
{
// 成员函数
Builder& setName(string n); // Builder& 返回类型 // setName 函数名
name = n;
return *this;
}
class Dog
{
string name;
void bark()
{
# this 是指向当前对象的指针
# *this 就是当前对象本身
cout << this -> name;
cout << (*this).name;
}
};
int main()
{
Dog d1,d2;
d1.bark(); // 函数内this指向d1
d2.bark(); // 函数内this指向d2
}
class Builder
{
string name;
int age;
Builder& setName(string n)
{ name = n; return *this; // 返回自己 }
Builder& setAge(int a)
{ age = a; return *this; // 返回自己 } };
Builder b; // 分开写
b.setName("Tom"); // 返回 b 自己
b.setAge(20); // 返回 b 自己
// 连起来写(链式调用)
b.setName("Tom").setAge(20);
// 等价于
(b.setName("Tom")).setAge(20);
// ↑ // 这里返回了 b 自己,所以可以继续调用 .setAge()
void setName(string n) { name = n; // 没有返回值 }
b.setName("Tom").setAge(20); // 错误!setName 返回 void,没法继续调用
Builder setName(string n)
{ name = n; return *this; // 返回一个拷贝! }
b.setName("Tom").setAge(20);
// ↑ // 这里返回的是 b 的副本,不是 b 本身
// setAge 修改的是副本,原来的 b 没变!
Builder& setName(string n)
{ name = n; return *this; // 返回自己的引用 }
b.setName("Tom").setAge(20);
// ↑ // 返回的就是 b 本身 // setAge 修改的也是 b