简体   繁体   English

在 C++ 中创建类对象

[英]Creating a class object in c++

First i am from JAVA.首先我来自JAVA。

In java we create class object like this.在java中,我们像这样创建类对象。

Example example=new Example();

The Example class can have constructor or cannot have constructor. Example 类可以有构造函数,也可以不能有构造函数。

I can use the same in c++ like this我可以像这样在 C++ 中使用相同的

Example* example=new Example();

Where constructor is compulsory.构造函数是强制性的。

From this tutorial http://www.cplusplus.com/doc/tutorial/classes/从本教程http://www.cplusplus.com/doc/tutorial/classes/

I got that we can create object like this.我知道我们可以创建这样的对象。

Example example;

Which do not require an constructor.其中不需要构造函数。

I have two questions.我有两个问题。

  1. What is the difference between both the way of creating class objects.两种创建类对象的方式有什么区别。

  2. If I am creating object like Example example;如果我正在创建类似Example example;对象Example example; how to use that in an singleton class.如何在单例类中使用它。

like I usually do like this.就像我通常这样做的那样。

Sample* Singleton::get_sample() {
    if (sample == NULL) {
        sample = new Sample();
    }
    return sample;
}

Please guide me if I am wrong.如果我错了,请指导我。

I can use the same in c++ like this [...] Where constructor is compulsory.我可以像这样在 C++ 中使用相同的 [...] 构造函数是强制性的。 From this tutorial I got that we can create object like this [...] Which do not require an constructor.本教程中我了解到我们可以创建这样的对象 [...] 不需要构造函数。

This is wrong.这是错误的。 A constructor must exist in order to create an object.必须存在构造函数才能创建对象。 The constructor could be defined implicitly by the compiler under some conditions if you do not provide any, but eventually the constructor must be there if you want an object to be instantiated.构造函数可以编译器隐式的一些条件下定义,如果你不提供任何,但最终如果你想要一个对象实例化的构造函数必须在那里。 In fact, the lifetime of an object is defined to begin when the constructor routine returns.事实上,对象的生命周期被定义为从构造函数返回时开始。

From Paragraph 3.8/1 of the C++11 Standard:来自 C++11 标准的第 3.8/1 段:

[...] The lifetime of an object of type T begins when: [...] T 类型对象的生命周期开始于:

— storage with the proper alignment and size for type T is obtained, and — 获得了类型 T 具有正确对齐和大小的存储,并且

— if the object has non-trivial initialization, its initialization is complete. — 如果对象具有非平凡的初始化,则其初始化已完成。

Therefore, a constructor must be present.因此,必须存在构造函数。

1) What is the difference between both the way of creating class objects. 1)这两种创建类对象的方式有什么区别。

When you instantiate object with automatic storage duration, like this (where X is some class):当您使用自动存储持续时间实例化对象时,如下所示(其中X是某个类):

X x;

You are creating an object which will be automatically destroyed when it goes out of scope.您正在创建一个对象,当它超出范围时将自动销毁。 On the other hand, when you do:另一方面,当你这样做时:

X* x = new X();

You are creating an object dynamically and you are binding its address to a pointer.您正在动态创建一个对象,并将其地址绑定到一个指针。 This way, the object you created will not be destroyed when your x pointer goes out of scope.这样,当您的x指针超出范围时,您创建的对象不会被销毁。

In Modern C++, this is regarded as a dubious programming practice: although pointers are important because they allow realizing reference semantics , raw pointers are bad because they could result in memory leaks (objects outliving all of their pointers and never getting destroyed) or in dangling pointers (pointers outliving the object they point to, potentially causing Undefined Behavior when dereferenced).在现代 C++ 中,这被认为是一种可疑的编程实践:尽管指针很重要,因为它们允许实现引用语义,但原始指针是不好的,因为它们可能导致内存泄漏(对象的生命周期超过其所有指针并且永远不会被销毁)或悬空指针(指针比它们指向的对象寿命更长,在取消引用时可能会导致未定义行为)。

In fact, when creating an object with new , you always have to remember destroying it with delete :事实上,当用new创建一个对象时,你总是要记住用delete销毁它:

delete x;

If you need reference semantics and are forced to use pointers, in C++11 you should consider using smart pointers instead:如果您需要引用语义并被迫使用指针,则在 C++11 中,您应该考虑使用智能指针

std::shared_ptr<X> x = std::make_shared<X>();

Smart pointers take care of memory management issues, which is what gives you headache with raw pointers.智能指针负责处理内存管理问题,这正是原始指针让您头疼的原因。 Smart pointers are, in fact, almost the same as Java or C# object references.实际上,智能指针几乎与 Java 或 C# 对象引用相同。 The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers. “几乎”是必要的,因为程序员必须注意不要通过拥有智能指针来引入循环依赖。

2) If i am creating object like Example example; 2)如果我正在创建像示例示例那样的对象; how to use that in an singleton class.如何在单例类中使用它。

You could do something like this (simplified code):你可以做这样的事情(简化代码):

struct Example
{
    static Example& instance()
    {
        static Example example;
        return example;
    }

 private:

    Example() { }
    Example(Example const&) = delete;
    Example(Example&&) = delete;
    Example& operator = (Example const&) = delete;
    Example& operator = (Example&&) = delete;

};
Example example;

This is a declaration of a variable named example of type Example .这是一个名为example的变量的声明,类型为Example This will default-initialize the object which involves calling its default constructor.这将默认初始化涉及调用其默认构造函数的对象。 The object will have automatic storage duration which means that it will be destroyed when it goes out of scope.该对象将具有自动存储持续时间,这意味着它在超出范围时将被销毁。

Example* example;

This is a declaration of a variable named example which is a pointer to an Example .这是一个名为example的变量的声明,它是一个指向Example指针 In this case, default-initialization leaves it uninitialized - the pointer is pointing nowhere in particular.在这种情况下,默认初始化使其未初始化 - 指针特别指向任何地方。 There is no Example object here.这里没有Example对象。 The pointer object has automatic storage duration.指针对象具有自动存储持续时间。

Example* example = new Example();

This is a declaration of a variable named example which is a pointer to an Example .这是一个名为example的变量的声明,它是一个指向Example指针 This pointer object, as above, has automatic storage duration.如上所述,这个指针对象具有自动存储持续时间。 It is then initialized with the result of new Example();然后用new Example();的结果初始化它new Example(); . . This new expression creates an Example object with dynamic storage duration and then returns a pointer to it.这个new表达式创建了一个具有动态存储持续时间的Example对象,然后返回一个指向它的指针。 So the example pointer is now pointing to that dynamically allocated object.所以example指针现在指向那个动态分配的对象。 The Example object is value-initialized which will call a user-provided constructor if there is one or otherwise initialise all members to 0. Example对象是值初始化的,如果有一个,它将调用用户提供的构造函数,否则将所有成员初始化为 0。

Example* example = new Example;

This is similar to the previous line.这与上一行类似。 The difference is that the Example object is default-initialized, which will call the default constructor of Example (or leave it uninitialized if it is not of class type).不同之处在于Example对象是默认初始化的,它将调用Example的默认构造函数(如果它不是类类型,则不初始化)。

A dynamically allocated object must be delete d (probably with delete example; ).动态分配的对象必须是delete d(可能与delete example; )。

There is two ways to make/create object in c++.在 C++ 中有两种创建/创建对象的方法。

First one is :第一个是:

MyClass myclass; // if you don;t need to call rather than default constructor    
MyClass myclass(12); // if you need to call constructor with parameters

Second one is :第二个是:

MyClass *myclass = new MyClass();// if you don;t need to call rather than default constructor
MyClass *myclass = new MyClass(12);// if you need to call constructor with parameters

In c++ if you use new keyword, object will be stored in heap.在 C++ 中,如果使用 new 关键字,对象将存储在堆中。 it;s very useful if you are using this object long time of period and if you use first method, it will be stored in stack.如果您长时间使用此对象,并且使用第一种方法,它将存储在堆栈中,这将非常有用。 it can be used only short time period.它只能在很短的时间内使用。 Notice : if you use new keyword, remember it will return pointer value.注意:如果你使用 new 关键字,记住它会返回指针值。 you should declare name with *.你应该用 * 声明名称。 If you use second method, it doesn;t delete object in the heap.如果使用第二种方法,它不会删除堆中的对象。 you must delete by yourself using delete keyword;您必须使用 delete 关键字自行删除;

delete myclass;

1)What is the difference between both the way of creating class objects. 1)这两种创建类对象的方式有什么区别。

First one is a pointer to a constructed object in heap (by new ).第一个是指向堆中构造对象的指针(通过new )。 Second one is an object that implicitly constructed.第二个是隐式构造的对象。 (Default constructor) (默认构造函数)

2)If i am creating object like Example example; 2)如果我正在创建像示例一样的对象; how to use that in an singleton class.如何在单例类中使用它。

It depends on your goals, easiest is put it as a member in class simply.这取决于您的目标,最简单的方法是将其简单地作为班级成员。

A sample of a singleton class which has an object from Example class:具有来自Example类的对象的单例类Example

class Sample
{

    Example example;

public:

    static inline Sample *getInstance()
    {
        if (!uniqeInstance)
        {
            uniqeInstance = new Sample;
        }
        return uniqeInstance;
    }
private:
    Sample();
    virtual ~Sample();
    Sample(const Sample&);
    Sample &operator=(const Sample &);
    static Sample *uniqeInstance;
};

1) What is the difference between both the way of creating class objects. 1)这两种创建类对象的方式有什么区别。

a) pointer a) 指针

Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:

delete example;

b) Simple declaration b) 简单声明

Example example;

you get a variable, not a pointer, and it will be destroyed out of scope it was declared.你得到的是一个变量,而不是一个指针,它会在它声明的范围之外被销毁。

2) Singleton C++ 2) 单例 C++

This SO question may helps you 这个问题可能对你有帮助

First of all, both cases calls a constructor.首先,这两种情况都调用了一个构造函数。 If you write如果你写

Example *example = new Example();

then you are creating an object, call the constructor and retrieve a pointer to it .然后您正在创建一个对象,调用构造函数并检索指向它的指针

If you write如果你写

Example example;

The only difference is that you are getting the object and not a pointer to it.唯一的区别是您获取的是对象而不是指向它的指针。 The constructor called in this case is the same as above, the default (no argument) constructor.在这种情况下调用的构造函数与上面相同,默认(无参数)构造函数。

As for the singleton question, you must simple invoke your static method by writing:至于单例问题,您必须通过编写简单地调用您的静态方法:

Example *e = Singleton::getExample();
Example example;

Here example is an object on the stack.这里的例子是堆栈上的一个对象。

Example* example=new Example();

This could be broken into:这可以分解为:

Example* example;
....
example=new Example();

Here the first statement creates a variable example which is a "pointer to Example".这里的第一条语句创建了一个变量 example,它是一个“指向 Example 的指针”。 When the constructor is called, memory is allocated for it on the heap (dynamic allocation).调用构造函数时,会在堆上为其分配内存(动态分配)。 It is the programmer's responsibility to free this memory when it is no longer needed.程序员有责任在不再需要时释放该内存。 (C++ does not have garbage collection like java). (C++ 没有像 java 那样的垃圾收集)。

In the first case you are creating the object on the heap using new .在第一种情况下,您使用newheap创建对象。 In the second case you are creating the object on the stack , so it will be disposed of when going out of scope.在第二种情况下,您在stack上创建对象,因此在超出范围时将对其进行处理。 In C++ you'll need to delete objects on the heap explicitly using delete when you don't Need them anymore.C++ ,当您不再需要它们时,您需要使用delete显式delete heap对象。

To call a static method from a class, do要从类调用静态方法,请执行

Singleton* singleton = Singleton::get_sample();

in your main-function or wherever.在您的主要功能或任何地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM