简体   繁体   English

复制构造函数指针对象

[英]Copy Constructor Pointer Object

I have the following class with the 2 pointers to block 我有下面的类与2个要阻止的指针

#ifndef SCORING_H
#define SCORING_H

#include "Block.h"
#include <iostream>
#include <vector>
#include <cstring>

using namespace std;

class Scoring
{
    public:
        Scoring(Block *, Block*, string, string, double);
        virtual ~Scoring();
        Scoring(const Block& b1, const Block &b2);
    private:
        Block * b1;
        Block * b2;
        string path1;
        string path2;
        double val;
};

#endif // SCORING_H

Class Block is the following: 类块如下:

class Block {
    public :
        ///constructo
        Block(double, double, double, double, int, vector<LineElement*>);

        ///Setter functions
        void setID(int);
        void setTop(double);
        void setLeft(double);
        void setRight(double);
        void setBottom(double);
        void setLine(vector<LineElement*>);

        int getID();
        double getTop();
        double getLeft();
        double getBottom();
        double getRight();
        vector<LineElement*> getLine();

    private:
        int id;
        vector<LineElement*> Listline;
        double top;
        double left;
        double bottom;
        double right;
};

#endif // ELEMENT_H_INCLUDED

I want to know, Should I construct a copy constructor for "Block * b1;Block * b2" and how can I treat these 2 points in the class scoring.h? 我想知道,是否应该为“ Block * b1; Block * b2”构造一个副本构造函数,以及如何在scoring.h类中处理这两点?

Thank you. 谢谢。

If you create a constructor other than plain and simple Block::Block(const Block&) then it's not a copy-constructor. 如果您创建的构造器不是简单而简单的Block::Block(const Block&)则它不是复制构造器。 If you want to make a constructor in Scoring taking two Block pointers it's most definitely is not a copy-constructor. 如果要在Scoring中使用两个Block指针构造一个构造函数,则绝对不是复制构造函数。

If you want a copy-constructor in Scoring it should be like this: 如果要在Scoring使用复制构造函数,它应该是这样的:

class Scoring
{
    // ...

    Scoring(const Scoring& other);

    // ...
};

Then in that constructor you copy from other : 然后在该构造函数中,从other复制:

Scoring::Scoring(const Scoring& other)
    : b1(new Block(*other.b1)),
      b2(new Block(*other.b2)),
      path1(other.path1),
      path2(other.path2),
      val(other.val)
{
}

Of course, you should probably make a copy-constructor for the Block class too, as it contains a vector of pointers, and if you don't you will have two vectors with pointers pointing to the same objects, and that will be bad when you delete these objects in one vector but not the other. 当然,您可能也应该为Block类创建一个复制构造函数,因为它包含一个指针向量,否则,您将有两个指针指向相同对象的向量,当指针指向相同对象时,这将是不好的您可以在一个矢量中删除这些对象,而在另一矢量中则不删除。

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

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