简体   繁体   English

C ++中带指针参数的函数

[英]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. Item类的构造函数需要一个指针,但我将一个对象传递给它,而不是指向该对象的指针。 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): 如果您不希望它有效,可以删除它(需要C ++ 11):

Item (const Item &) = delete;

If your compiler doesn't support C++11, you can just declare it private. 如果您的编译器不支持C ++ 11,您可以将其声明为私有。

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&);

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

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