我有以下带有 2 个 block 指针的类
#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
类 block 如下:
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
我想知道,我是否应该为“Block * b1;Block * b2”构造一个复制构造函数,我该如何处理类scoring.h中的这2个点?
谢谢。
最佳答案
如果您创建的构造函数不是简单明了的Block::Block(const Block&)
,那么它就不是复制构造函数。如果您想在 Scoring
中使用两个 Block
指针创建构造函数,那么它绝对不是复制构造函数。
如果你想在 Scoring
中使用复制构造函数,它应该是这样的:
class Scoring
{
// ...
Scoring(const Scoring& 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)
{
}
当然,您也应该为 Block
类创建一个复制构造函数,因为它包含一个指针 vector ,如果不这样做,您将有两个 vector 指向相同的对象,当您在一个 vector 中删除这些对象而不是另一个 vector 时,这将很糟糕。
关于c++ - 复制构造函数指针对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16836928/