簡體   English   中英

如何使用對象指針而不是對象編寫賦值運算符/復制構造函數?

[英]How to write assignment operator /copy constructor using object pointers rather than objects?

我看到很多例子解釋了如何為對象編寫賦值運算符/復制構造函數,但是,當涉及到對象指針時,我很掙扎。 附上示例代碼。

我想讓 test2(test1) 調用復制構造函數,但它似乎沒有調用用戶指定的復制構造函數。

#include <vector>
#include <iostream>
#include <memory>

template <class fd>
class node
{
    public:
//    private:
        std::vector <fd> data_point;
        std::shared_ptr< node <fd> > left;
        std::shared_ptr< node <fd> > right;
        bool collision;

//    public:
        node(std::vector <fd> &data, bool level=0);
        ~node();
        node(const node <fd> &old);
        void check_point();
};

template <class fd>
node <fd>::node(std::vector <fd> &data, bool level)
{
    if (level) throw std::invalid_argument( "Error->Duplicate data" );
    else
    {
        data_point = data;
        left = nullptr;
        right = nullptr;
        collision = level;
    }
}

template <class fd>
node <fd>::~node() {}

template <class fd>
node <fd>::node(const node <fd> &old)
{
    std::cout<<"Copy constructor called"<<std::endl;
//    this->data_point = old.data_point;
//    this->left = new node <fd> (old.left);
//    this->right = new node <fd> (old.right);
//    this->collision = old.collision;
}

template <class fd>
void node <fd>::check_point()
{
    if (this == nullptr)
    {
        std::cout<<"It's a leaf node with None"<<std::endl;
    }
    else
    {
        for (int dim=0; dim<this->data_point.size(); dim++)
        {
            std::cout<<data_point[dim]<<" ";
        }
        std::cout<<std::endl;
    }
}

int main()
{
    std::vector <double> data;
    data = {50};
    std::shared_ptr <node <double> > test1 = std::make_shared <node <double> > (data);
//    std::cout << typeid(test1).name() << std::endl;
    test1->check_point();//Prints 50.Expected
    std::shared_ptr <node <double> > test2(test1);//Expecting copyconstructor call for deep copy
    test1->data_point = {75};//Changing value
    test2->check_point();//If deep copy happened, value would not change. Default copy constructor does not shallow copy and hence value does not change.
    test1->check_point();
    return 0;
}

如果你能解釋如何做到這一點,那就太好了。

在上述程序中觸發使用復制構造函數的最小更改:

//std::shared_ptr <node <double> > test2(test1);//Expecting copyconstructor call for deep copy
std::shared_ptr <node <double> > test2 = std::make_shared <node <double> >(*test1);

新行將取消引用test1的指針並將其傳遞給構造test2的構造函數,從而調用復制構造函數。

新輸出:

50
Copy constructor called

75

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM