C++ 匿名对象
一、什么是匿名对象
匿名对象 :没有变量名、临时创建的类对象,用完立刻销毁。
语法:
cpp
类名(); // 无参匿名对象
类名(参数); // 有参匿名对象
特点:
-
没有名字,不能后续再使用
-
创建出来马上用,语句结束立即析构
-
常用于:传参、返回值、简化代码
二、最简代码:认识匿名对象
cpp
#include <iostream>
using namespace std;
class Person
{
public:
Person()
{
cout << "构造函数执行" << endl;
}
~Person()
{
cout << "析构函数执行" << endl;
}
};
int main()
{
// 普通有名对象
cout << "--- 有名对象 ---" << endl;
Person p;
// 匿名对象:没有名字
cout << "\n--- 匿名对象 ---" << endl;
Person();
return 0;
}
输出规律:
-
有名对象:main 结束才析构
-
匿名对象:当前语句结束 立刻析构
三、有参构造的匿名对象
cpp
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string name;
public:
Student(string n) : name(n)
{
cout << "构造:" << name << endl;
}
~Student()
{
cout << "析构" << endl;
}
};
int main()
{
// 有参匿名对象
Student("张三");
cout << "匿名对象已经销毁了" << endl;
return 0;
}
四、匿名对象直接调用成员函数
不用定义变量名,直接 类名().函数()
cpp
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
void show()
{
cout << "我是匿名对象调用的函数" << endl;
}
};
int main()
{
// 匿名对象直接调用成员函数
Person().show();
return 0;
}
五、匿名对象作函数参数(最常用场景)
cpp
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string name;
Person(string n) : name(n) {}
};
void printInfo(Person p)
{
cout << "姓名:" << p.name << endl;
}
int main()
{
// 传匿名对象做实参
printInfo(Person("李四"));
return 0;
}
优点:不用单独定义有名对象,代码更简洁
六、函数返回匿名对象
cpp
#include <iostream>
using namespace std;
class Point
{
public:
int x, y;
Point(int a, int b) : x(a), y(b) {}
};
Point getPoint()
{
// 返回匿名对象
return Point(10, 20);
}
int main()
{
Point p = getPoint();
cout << p.x << " " << p.y << endl;
return 0;
}
七、匿名对象 等价 隐式类型转换
Person("张三") 匿名对象,也可以看成类型转换
cpp
// 用匿名对象赋值
Person p = Person("王五");
// 等价隐式转换
Person p2 = "王五";
八、易错坑:匿名对象 别和 函数声明 搞混
cpp
class Person {};
int main()
{
Person p1; // 正常定义对象
// 易错!不是匿名对象,是函数声明
Person p2();
return 0;
}
记住:无参匿名对象写法是 Person();,不能带变量名
九、匿名对象 生命周期重点
-
匿名对象创建后,当前语句结束立刻调用析构;
-
有名对象出作用域才析构;
-
匿名对象适合临时使用、传参、返回值;
-
匿名对象没有名字,不能重复使用;
-
可以直接调用成员函数、作为函数实参。
十、核心总结(考试必背)
-
匿名对象:无变量名,临时对象;
-
格式:
类名()、类名(参数); -
生命周期:用完立即销毁;
-
用途:临时调用成员函数、函数传参、函数返回值;
-
区分:
Person();匿名对象,Person p();是函数声明。