简体   繁体   English

将指针传递给 class 的构造函数

[英]Passing pointer to constructor of class

I'm not quite sure what the difference between passing *d and d2 to the constructor is:我不太确定将*dd2传递给构造函数之间的区别是:

#include <iostream>

using namespace std;

class Data
{

public:
    int number;
};

class Node {

public:

    Data data;  

    Node() {};

    Node(Data d) : data(d) {};

};

int main()
{
    
    Data* d = new Data();
    Node* n = new Node(*d);
    
    Data d2;
    Node* n2 = new Node(d2);


    return 0;
} 

I can pass *d and d2, but in both scenarios, the data member "data" in the class "Node" is still an object by itself, is that correct?我可以通过 *d 和 d2,但是在这两种情况下,class“节点”中的数据成员“数据”本身仍然是 object,对吗? Or is there even a difference between passing an object and a dynamic object?或者通过 object 和动态 object 之间甚至有区别吗?

From Node 's perspective, the constructor receives a Data object.Node的角度来看,构造函数接收到一个Data object。 It doesn't care if this object is dynamically allocated using new or not.它不关心这个 object 是否使用new动态分配。

from node perspective, the constructor of node need an object of type data,so it only care about data object type, it don't care about its place in memory (static memory or dynamic memory) *d and d2 represent data objects so your code is correct. from node perspective, the constructor of node need an object of type data,so it only care about data object type, it don't care about its place in memory (static memory or dynamic memory) *d and d2 represent data objects so your代码是正确的。

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

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