在 C++ 中创建类对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15310846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:14:59  来源:igfitidea点击:

Creating a class object in c++

c++

提问by Kathick

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.

1)这两种创建类对象的方式有什么区别。

2)If i am creating object like Example example;how to use that in an singleton class.

2)如果我正在创建对象,例如Example example;如何在单例类中使用它。

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.

如果我错了,请指导我。

回答by Andy Prowl

I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorialI got that we can create object like this [...] Which do not require an constructor.

我可以像这样在 C++ 中使用相同的 [...] 构造函数是强制性的。从本教程中我了解到我们可以创建这样的对象 [...] 不需要构造函数。

This is wrong. A constructor must existin order to create an object. The constructor couldbe 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:

— storage with the proper alignment and size for type T is obtained, and

— if the object has non-trivial initialization, its initialization is complete.

[...] T 类型对象的生命周期开始于:

— 获得了类型 T 具有正确对齐和大小的存储,并且

— 如果对象具有非平凡的初始化,则其初始化已完成。

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 Xis 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 notbe destroyed when your xpointer 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, rawpointers 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 alwayshave 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 pointersinstead:

如果您需要引用语义并被迫使用指针,则在 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, almostthe same as Java or C# object references. The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers.

智能指针负责处理内存管理问题,这正是原始指针让您头疼的原因。实际上,智能指针几乎与 Java 或 C# 对象引用相同。“几乎”是必要的,因为程序员必须注意不要通过拥有智能指针来引入循环依赖。

2) If i am creating object like Example example; how to use that in an singleton class.

2)如果我正在创建像示例示例那样的对象;如何在单例类中使用它。

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;

};

回答by Joseph Mansfield

Example example;

This is a declaration of a variable named exampleof type 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.

这是一个名为exampletype的变量的声明Example。这将默认初始化涉及调用其默认构造函数的对象。该对象将具有自动存储持续时间,这意味着它在超出范围时将被销毁。

Example* example;

This is a declaration of a variable named examplewhich is a pointerto an Example. In this case, default-initialization leaves it uninitialized - the pointer is pointing nowhere in particular. There is no Exampleobject here. The pointer object has automatic storage duration.

这是一个命名的变量的声明example这是一个指针到一个Example。在这种情况下,默认初始化使其未初始化 - 指针特别指向任何地方。这里没有Example对象。指针对象具有自动存储持续时间。

Example* example = new Example();

This is a declaration of a variable named examplewhich is a pointerto an Example. This pointer object, as above, has automatic storage duration. It is then initialized with the result of new Example();. This newexpression creates an Exampleobject with dynamic storage duration and then returns a pointer to it. So the examplepointer is now pointing to that dynamically allocated object. The Exampleobject is value-initialized which will call a user-provided constructor if there is one or otherwise initialise all members to 0.

这是一个命名的变量的声明example这是一个指针到一个Example。如上所述,这个指针对象具有自动存储持续时间。然后用 的结果初始化它new Example();。此new表达式创建一个Example具有动态存储持续时间的对象,然后返回一个指向它的指针。所以example指针现在指向那个动态分配的对象。该Example对象是值初始化的,如果有一个,它将调用用户提供的构造函数,否则将所有成员初始化为 0。

Example* example = new Example;

This is similar to the previous line. The difference is that the Exampleobject 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 deleted (probably with delete example;).

动态分配的对象必须是deleted (可能带有delete example;)。

回答by Vishva Rodrigo

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. 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. 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;

在 C++ 中,如果使用 new 关键字,对象将存储在堆中。如果您长时间使用此对象,并且使用第一种方法,它将存储在堆栈中,这将非常有用。它只能在很短的时间内使用。注意:如果你使用 new 关键字,记住它会返回指针值。你应该用 * 声明名称。如果使用第二种方法,它不会删除堆中的对象。您必须使用 delete 关键字自行删除;

delete myclass;

回答by Fèlix Galindo Allué

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 nota 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();

回答by masoud

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). Second one is an object that implicitly constructed. (Default constructor)

第一个是指向堆中构造对象的指针(by new)。第二个是隐式构造的对象。(默认构造函数)

2)If i am creating object like Example example; how to use that in an singleton class.

2)如果我正在创建像示例一样的对象;如何在单例类中使用它。

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 Exampleclass:

具有来自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;
};

回答by Miguel Prz

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 questionmay helps you

这个问题可能对你有帮助

回答by uba

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". 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).

这里的第一条语句创建了一个变量 example,它是一个“指向 Example 的指针”。调用构造函数时,会在堆上为其分配内存(动态分配)。程序员有责任在不再需要时释放该内存。(C++ 没有像 java 那样的垃圾收集)。

回答by bash.d

In the first case you are creating the object on the heapusing new. In the second case you are creating the object on the stack, so it will be disposed of when going out of scope. In C++you'll need to delete objects on the heapexplicitly using deletewhen you don't Need them anymore.

在第一种情况下,您是在heapusing上创建对象new。在第二种情况下,您在 上创建对象stack,因此当超出范围时它将被处理掉。在C++您不再需要它们时,您需要删除heap显式使用的对象delete

To call a static method from a class, do

要从类调用静态方法,请执行

Singleton* singleton = Singleton::get_sample();

in your main-function or wherever.

在您的主要功能或任何地方。