《C++ 匿名对象》

匿名对象通常具有如下特点:

  1. 没有变量引用的对象。
  2. 匿名对象的目的用于及时使用(一次使用)。
  3. 匿名对象作为参数传递给函数。
  4. 用于减少内存消耗。

 

生命周期:

匿名对象的生命周期,只存在于当前代码的这一行,遇到;结束。

 

定义:

Classname({parameters});

 

例子:

#include <iostream>
 
class Add
{
public:
    Add()
    {
        std::cout << "Default Add constructor." << std::endl;
    }
    Add(int a, int b) : a_(a), b_(b)
    {
        std::cout << "Parameterised Add constructor." << std::endl;
    }
    ~Add()
    {
        std::cout << "Destructor executed." << std::endl;
    }
 
private:
    int a_;
    int b_;
};
 
int main() {
    // Creation of  Anonymous Object
    Add();
    // Creation of  Anonymous Object
    Add(10, 45);
    return 0;
}

运行上面的程序,得到如下结果:

Default Add constructor.
Destructor executed.
Parameterised Add constructor.
Destructor executed.

  上面是一个很简单的Add类,从输出结果可以看出来,匿名对象和普通对象创建的过程是一样的。

 

在匿名对象的帮助下调用成员函数

  有些时候我们需要调用某个对象的方法,调用完就不再需要该对象,可以通过匿名对象来实现。好处是,匿名对象节省了创建对象的时间,也节省了内存。语法如下:

Classname({parameters}). function name({parameters});

具有如下代码:

#include <iostream>
 
class Add
{
public:
    Add()
    {
        std::cout << "Default Add constructor." << std::endl;
    }
    Add(int a, int b) : a_(a), b_(b)
    {
        std::cout << "Parameterised Add constructor." << std::endl;
    }
    ~Add()
    {
        std::cout << "Destructor executed." << std::endl;
    }
    void display()
    {
        std::cout << a_ << "\t" << b_ << std::endl;
    }
 
private:
    int a_ = 0;
    int b_ = 0;
};
 
int main()
{
    // Creation of  Anonymous Object
    Add().display();
    // Creation of  Anonymous Object
    Add(10, 45).display();
    return 0;
}

执行上面代码,可以得到如下输出:

Default Add constructor.
0       0
Destructor executed.
Parameterised Add constructor.
10      45
Destructor executed.

  当调用完display方法后,匿名对象随之就会销毁,不占用内存。

 

运算符重载中匿名对象的使用

 如果一个对象使用后不再被引用,建议使用匿名对象。下面的例子重载了+号运算符,有两个对象只做临时使用。
// C++ program to illustrate the
// concept of anonymous object
#include <iostream>
#include <string>
using namespace std;
 
// Private datamembers
class Complex {
    int real, img;
 
public:
    // Default constructor
    Complex() {}
 
    // Parameterised Constructor
    Complex(int r, int i)
    {
        real = r;
        img = i;
    }
 
    // getter
    int getReal() { return real; }
 
    // getter
    int getImg() { return img; }
 
    // Operator overloading function
    Complex operator+(Complex c)
    {
        Complex temp;
        temp.real = this->real + c.real;
        temp.img = this->img + c.img;
        return temp;
    }
 
    string name()
    {
        return std::to_string(real) + "+" + std::to_string(img) + "i";
    }
};
 
// Driver Function
int main()
{
    Complex c3;
    c3 = Complex({ 2, 3 }) + Complex({ 5, 6 });
 
    cout << c3.name() << endl;
 
    return 0;
}

执行上面代码得到输出:

7+9i

 

posted @ 2023-05-18 18:08  一个不知道干嘛的小萌新  阅读(213)  评论(0编辑  收藏  举报