C++中的匿名类

匿名类是一个没有名字的类。C++支持这个特性。

null
  • 这些类不能有构造函数,但可以有析构函数。
  • 这些类既不能作为参数传递给函数,也不能用作函数的返回值。

举例说明匿名类

  1. 创建匿名类的单个对象: 在第一个示例中,使用对象名obj1创建匿名类。obj1的范围贯穿整个项目。所以,我们可以在主函数中访问它。主要是使用obj1,调用匿名类的成员函数。

    // CPP program to illustrate
    // concept of Anonymous Class
    #include <iostream>
    using namespace std;
    // Anonymous Class : Class is not having any name
    class
    {
    // data member
    int i;
    public :
    void setData( int i)
    {
    // this pointer is used to differentiate
    // between data member and formal argument.
    this ->i = i;
    }
    void print()
    {
    cout << "Value for i : " << this ->i << endl;
    }
    } obj1; // object for anonymous class
    // Driver function
    int main()
    {
    obj1.setData(10);
    obj1.print();
    return 0;
    }

    
    

    输出:

    Value for i : 10
    
  2. 创建匿名类的两个对象: 在第二个示例中,我们为匿名类创建了两个对象obj1和obj2,并调用了该类的成员函数。obj1和obj2的范围贯穿整个程序。同样,我们可以为一个匿名类创建多个对象。

    // CPP program to illustrate
    // concept of Anonymous Class
    #include <iostream>
    using namespace std;
    // Anonymous Class : Class is not having any name
    class
    {
    // data member
    int i;
    public :
    void setData( int i)
    {
    // this pointer is used to differentiate
    // between data member and formal argument.
    this ->i = i;
    }
    void print()
    {
    cout << "Value for i : " << this ->i << endl;
    }
    } obj1, obj2; // multiple objects for anonymous class
    // Driver function
    int main()
    {
    obj1.setData(10);
    obj1.print();
    obj2.setData(20);
    obj2.print();
    return 0;
    }

    
    

    输出:

    Value for i : 10
    Value for i : 20
    
  3. 限制匿名类的范围: 为了限制匿名类的对象范围,我们可以借助typedef。在第三个示例中,使用 类型定义 我们可以给类指定一个方便的名称,并使用该名称,我们已经为匿名类创建了多个对象obje1和obj2。在这里,我们可以控制obj1和obj2对象的范围,它们位于主函数内。

    // CPP program to illustrate
    // concept of Anonymous Class
    // by scope restriction
    #include<iostream>
    using namespace std;
    // Anonymous Class : Class is not having any name
    typedef class
    {
    // data member
    int i;
    public :
    void setData( int i)
    {
    // this pointer is used to differentiate
    // between data member and formal argument.
    this ->i = i;
    }
    void print()
    {
    cout << "Value for i :" << this ->i << endl;
    }
    } myClass; // using typedef give a proper name
    // Driver function
    int main()
    {
    // multiple objects
    myClass obj1, obj2;
    obj1.setData(10);
    obj1.print();
    obj2.setData(20);
    obj2.print();
    return 0;
    }

    
    

    输出:

    Value for i : 10
    Value for i : 20
    
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享