简体   繁体   English

传递引用与指针

[英]Passing in References vs. Pointers

I am getting an error when I pass in newTemp to setEmergencyContact() . newTemp传递给setEmergencyContact()时出现错误。 The error I get is in regards to: 我得到的错误是关于:

temp->Contact::setEmergencyContact(newTemp);

"error: no matching function call to 'Contact::setEmergencyContact(*&Contact)'" “错误:没有匹配的函数调用'Contact :: setEmergencyContact(*&Contact)'”

So my question is: If you have to create a object by using a pointer, how do you pass the object to a function that uses a reference not a pointer? 所以我的问题是:如果必须使用指针创建对象,那么如何将对象传递给使用引用而不是指针的函数?

 Contact generateRandomContact(){
        // The name will be created with
        // generateRandomName() and phone number will be created with
        // generateRandomNumber(). Using the above random function,
        // with 50% probability assign a new Contact as the emergencyContact
        // of the one just generated. Otherwise leave it NULL (default).
        // Then return this Contact.

Contact* temp = new Contact;
temp->Contact::changeName(generateRandomName());
temp->Contact::changeNumber(generateRandomNumber());
    if(myrand(11) % 2 != 0){
      Contact* newTemp = new Contact;
      temp->Contact::setEmergencyContact(newTemp);
   }

return *temp;  
}

Emergency Contact Function: 紧急联络功能:

void Contact::setEmergencyContact(Contact & _emergencyContact){
Contact* changeEmergencys = new Contact;
changeEmergencys = emergencyContact->getEmergencyContact();
}

取消引用:

temp->setEmergencyContact(*newTemp)
void Contact::setEmergencyContact(Contact & _emergencyContact)

Should be either just 应该只是

void Contact::setEmergencyContact(Contact * _emergencyContact)

to work with your code, still using -> instead of . 使用您的代码,仍然使用->而不是. .

However, if you want to modify the pointer itself, you can use 但是,如果要修改指针本身,则可以使用

void Contact::setEmergencyContact(Contact* & _emergencyContact) {
    Contact* changeEmergencys = new Contact;
    changeEmergencys = _emergencyContact->getEmergencyContact();
}

Note that if you dereferenced it, you would have to use . 请注意,如果取消引用它,则必须使用. instead of -> 代替->

void Contact::setEmergencyContact(Contact & _emergencyContact) {
    Contact* changeEmergencys = new Contact;
    changeEmergencys = _emergencyContact.getEmergencyContact();
}

Edit the function to take a pointer instead: 编辑函数以改用指针:

void Contact::setEmergencyContact(Contact * _emergencyContact)

Or dereference the passing pointer as zmbq suggested. 或按照zmbq建议取消引用传递的指针。

I see that you are using much new and delete I can't help myself but to recommend smart pointers and minimize the use of new and delete. 我看到您正在使用很多new和Delete,我不禁要推荐智能指针,并尽量减少使用new和Delete。

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

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