C++ 知识点19 匿名对象

C++ 匿名对象

一、什么是匿名对象

匿名对象 :没有变量名、临时创建的类对象,用完立刻销毁。

语法:

cpp 复制代码
类名();         // 无参匿名对象
类名(参数);     // 有参匿名对象

特点:

  1. 没有名字,不能后续再使用

  2. 创建出来马上用,语句结束立即析构

  3. 常用于:传参、返回值、简化代码


二、最简代码:认识匿名对象

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();,不能带变量名


九、匿名对象 生命周期重点

  1. 匿名对象创建后,当前语句结束立刻调用析构

  2. 有名对象出作用域才析构;

  3. 匿名对象适合临时使用、传参、返回值

  4. 匿名对象没有名字,不能重复使用;

  5. 可以直接调用成员函数、作为函数实参。


十、核心总结(考试必背)

  1. 匿名对象:无变量名,临时对象

  2. 格式:类名()类名(参数)

  3. 生命周期:用完立即销毁

  4. 用途:临时调用成员函数、函数传参、函数返回值;

  5. 区分:Person(); 匿名对象,Person p(); 是函数声明。

相关推荐
伊玛目的门徒4 分钟前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry30 分钟前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵2 小时前
【无标题】
数据结构·算法
逝水无殇2 小时前
C# 异常处理详解
开发语言·后端·c#
Kx_Triumphs3 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎4 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
玖玥拾4 小时前
C# 语言进阶(十五)C# 游戏服务端 MySQL 数据库
服务器·开发语言·网络·数据库·mysql·c#
铅笔侠_小龙虾4 小时前
Rust 学习目录
开发语言·学习·rust
Darkwanderor4 小时前
对Linux的进程控制的研究
linux·运维·c++