简体   繁体   中英

Passing in References vs. Pointers

I am getting an error when I pass in newTemp to setEmergencyContact() . The error I get is in regards to:

temp->Contact::setEmergencyContact(newTemp);

"error: no matching function call to '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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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