C++ 指向对象的指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2988273/
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-28 11:42:43  来源:igfitidea点击:

C++ pointer to objects

c++objectpointers

提问by Tony The Lion

In C++ do you always have initialize a pointer to an object with the newkeyword?

在 C++ 中,您是否总是使用new关键字初始化指向对象的指针?

Or can you just have this too:

或者你也可以拥有这个:

MyClass *myclass;

myclass->DoSomething();

I thought this was a pointer allocated on the stack instead of the heap, but since objects are normally heap allocated, I think my theory is probably faulty??

我认为这是在堆栈上而不是堆上分配的指针,但由于对象通常是堆分配的,我认为我的理论可能有问题??

Please advice.

请指教。

回答by

No, you can have pointers to stack allocated objects:

不,您可以拥有指向堆栈分配对象的指针:

MyClass *myclass;
MyClass c;
myclass = & c;
myclass->DoSomething();

This is of course common when using pointers as function parameters:

当使用指针作为函数参数时,这当然很常见:

void f( MyClass * p ) {
    p->DoSomething();
}

int main() {
    MyClass c;
    f( & c );
}

One way or another though, the pointer must always be initialised. Your code:

无论如何,指针必须始终被初始化。您的代码:

MyClass *myclass;
myclass->DoSomething();

leads to that dreaded condition, undefined behaviour.

导致可怕的情况,未定义的行为

回答by Naveen

No you can not do that, MyClass *myclasswill define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.

不,你不能那样做,MyClass *myclass将定义一个指向随机内存位置的指针(指针的内存分配在堆栈上)。尝试使用此指针将导致未定义的行为。

In C++, you can create objects either on stack or heap like this:

在 C++ 中,您可以像这样在堆栈或堆上创建对象:

MyClass myClass;
myClass.DoSomething();

Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClassvariable goes out of scope.

上面将在堆栈上分配 myClass (我认为标准中没有这个术语,但为了清楚起见,我使用了这个术语)。当myClass变量超出范围时,为对象分配的内存会自动释放。

Other way of allocating memory is to do a new. In that case, you have to take care of releasing the memory by doing deleteyourself.

分配内存的其他方法是执行new. 在这种情况下,你必须delete自己做来释放内存。

MyClass* p = new MyClass();
p->DoSomething();
delete p;

Remeber the deletepart, else there will be memory leak.

记住这delete部分,否则会有内存泄漏。

I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.

我总是喜欢尽可能使用堆栈分配的对象,因为我不必担心内存管理。

回答by Johan Kotlinski

if you want the object on the stack, try this:

如果你想要堆栈上的对象,试试这个:

MyClass myclass;
myclass.DoSomething();

If you need a pointer to that object:

如果您需要指向该对象的指针:

MyClass* myclassptr = &myclass;
myclassptr->DoSomething();

回答by Malith

First I need to say that your code,

首先我需要说你的代码,

MyClass *myclass;
myclass->DoSomething();

will cause an undefined behavior. Because the pointer "myclass" isn't pointing to any "MyClass" type objects.

将导致未定义的行为。因为指针“myclass”不指向任何“MyClass”类型的对象。

Here I have three suggestions for you:-

在这里,我给你三个建议:-

option 1:-You can simply declare and use a MyClass type object on the stack as below.

选项 1:-您可以简单地在堆栈上声明和使用 MyClass 类型对象,如下所示。

MyClass myclass; //allocates memory for the object "myclass", on the stack.
myclass.DoSomething();

option 2:-By using the new operator.

选项 2:-通过使用 new 运算符。

MyClass *myclass = new MyClass();

Three things will hapen here.

这里会发生三件事。

i) Allocates memory for the "MyClass" type object on the heap.

i) 为堆上的“MyClass”类型对象分配内存。

ii) Allocates memory for the "MyClass" type pointer "myclass" on the stack.

ii) 为堆栈上的“MyClass”类型指针“myclass”分配内存。

iii) pointer "myclass" points to the memory address of "MyClass" type object on the heap

iii) 指针“myclass”指向堆上“MyClass”类型对象的内存地址

Now you can use the pointer to access member functionsof the object after dereferencing the pointer by "->"

现在您可以在通过“->”取消引用指针后使用指针访问对象的成员函数

myclass->DoSomething();

But you should free the memory allocated to "MyClass" type object on the heap, before returning from the scope unless you want it to exists. Otherwise it will cause a memory leak!

但是您应该在从作用域返回之前释放分配给堆上“MyClass”类型对象的内存,除非您希望它存在。否则会造成内存泄漏

delete myclass; // free the memory pointed by the pointer "myclass"

option 3:-you can also do as below.

选项 3:-您也可以按以下方式操作。

MyClass myclass; // allocates memory for the "MyClass" type object on the stack.
MyClass *myclassPtr; // allocates memory for the "MyClass" type pointer on the stack.
myclassPtr = &myclass; // "myclassPtr" pointer points to the momory address of myclass object.

Now, pointer and object both are on the stack. Now you can't return this pointer to the outside of the current scope because both allocated memory of the pointer and the object will be freed while stepping outside the scope.

现在,指针和对象都在堆栈上。现在您不能将此指针返回到当前作用域之外,因为指针和对象的分配内存都将在超出作用域时被释放。

So as a summary, option 1 and 3 will allocate an object on the stack while only the option 2 will do it on the heap.

因此,总而言之,选项 1 和 3 将在堆栈上分配一个对象,而只有选项 2 会在堆上分配对象。

回答by harsha217

if you want to access a method :

如果你想访问一个方法:

1) while using an object of a class:

1) 在使用类的对象时:

Myclass myclass;
myclass.DoSomething();

2) while using a pointer to an object of a class:

2)同时使用指向类对象的指针:

Myclass *myclass=&abc;
myclass->DoSomething();

回答by Parth Kothari

If you have defined a method inside your class as static, this is actually possible.

如果你在你的类中定义了一个静态方法,这实际上是可能的。

    class myClass
    {
    public:
        static void saySomething()
        {
            std::cout << "This is a static method!" << std::endl;
        }
    }; 

And from main, you declare a pointer and try to invoke the static method.

从 main 开始,您声明一个指针并尝试调用静态方法。

    myClass * pmyClass;
    pmyClass->saySomething();

/*    
Output:
This is a static method!
*/

This works fine because static methods do not belong to a specific instance of the class and they are not allocated as a part of any instance of the class.

这工作正常,因为静态方法不属于类的特定实例,并且它们不作为类的任何实例的一部分分配。

Read more on static methods here: http://en.wikipedia.org/wiki/Static_method#Static_methods

在此处阅读有关静态方法的更多信息:http: //en.wikipedia.org/wiki/Static_method#Static_methods

回答by Ali Soltani

Simple solution for cast pointer to object

将指针转换为对象的简单解决方案

Online demo

在线演示

class myClass
{
  public:
  void sayHello () {
    cout << "Hello";
  }
};

int main ()
{
  myClass* myPointer;
  myClass myObject = myClass(* myPointer); // Cast pointer to object
  myObject.sayHello();

  return 0;
}