简体   繁体   中英

Functions with pointer arguments in C++

I'm having some difficulties in understanding some aspects of functions with pointers. Here is the code I'm running:

#include <iostream>

using namespace std;

class Item
{
public:

    Item(Item * it)
    {
        data = it->data;
    }

    Item(int d)
    {
        data = d;
    }

    void printData()
    {
        cout << data << endl;
    }

private:
    int data;
};

int main()
{
    Item i1(79);
    Item i2(i1);

    i1.printData();
    i2.printData();
}

This code works, the problem is that I don't understand why! The constructor for the Item class needs a pointer, but I'm passing an object to it, not a pointer to the object. The code also works if I actually pass the pointer by using:

Item i2(&i1);

So, is the ampersand optional? Does the compiler recognise that I meant to pass a pointer instead of the actual object and take care of that by itself? I expect a compiling error in this kind of situation. I get very frustrated if my code works when it shouldn't :-)

Item i2(i1);

This works because it is not calling your user-defined constructor which takes a pointer, it is calling the implicitly generated copy-constructor which has the signature:

Item (const Item &);

If you don't want this to be valid, you can delete it (requires C++11):

Item (const Item &) = delete;

If your compiler doesn't support C++11, you can just declare it private.

compiler will generate copy constructor and assign value function, if you don't want to use these 2 function. you need declare it in private scope of class

private:
     Item(const Item&);
     Item& operator=(const Item&);

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