代码如下,写了一个类,然后构造函数用深拷贝的方法,重载赋值运算符,也用的深拷贝的方法。出错了
#ifndef _OPERATOR_H_
#define _OPERATOR_H_
#include <iostream>
using namespace std;
class Opeassignment
{
public:
int m_age;
int *m_score;
Opeassignment();
Opeassignment(int age, int score);
Opeassignment(const Opeassignment& p);
Opeassignment& operator=(const Opeassignment& p);
~Opeassignment();
};
void operatormain();
ostream& operator<< (ostream &cout, const Opeassignment &p);
#endif
#include "operator.h"
void operatormain() {
cout << endl << __FILE__ << ":" << __func__ << " line: " << __LINE__ << endl;
Opeassignment k1(18,99);
cout << "k1.m_age :" << k1.m_age << "\tk1.m_score :" << *k1.m_score << endl;
Opeassignment k2;
k2.m_age = 20;
*k2.m_score = 100;
cout << "k2.m_age :" << k2.m_age << "\tk2.m_score :" << *k2.m_score << endl;
**##error : Segmentation fault (core dumped)!**
Opeassignment k3(k2);
cout << "k3.m_age :" << k3.m_age << "\tk3.m_score :" << *k3.m_score << endl;
Opeassignment k4 = k2;
cout << "k4.m_age :" << k4.m_age << "\tk4.m_score :" << *k4.m_score << endl;
}
ostream& operator<< (ostream &cout, const Opeassignment &p) {
cout << __FILE__ << ": " << __func__ << ": " << __LINE__ << endl;
cout << "Age : " << p.m_age << "\tScore : " << *p.m_score;
return cout;
}
Opeassignment::Opeassignment() {
m_score = new int();
}
Opeassignment::Opeassignment(int age, int score) {
m_age = age;
m_score = new int(score);
}
Opeassignment::Opeassignment(const Opeassignment& p) {
m_age = p.m_age;
if(m_score != NULL) {
delete m_score;
m_score = NULL;
}
m_score = new int(*p.m_score);
}
Opeassignment& Opeassignment::operator=(const Opeassignment& p){
m_age = p.m_age;
if(m_score != NULL) {
delete m_score;
m_score = NULL;
}
m_score = new int(*p.m_score);
return *this;
}
Opeassignment::~Opeassignment() {
if(m_score != NULL) {
delete m_score;
m_score = NULL;
}
}
有大佬能帮忙看看为什么回报错呢,编译环境是G++,linux中编译的,报错内容是:##error : Segmentation fault (core dumped)!
具体是在进行类的拷贝时,以及用等号进行赋值时,会报错感觉是深拷贝有问题,现在正在学习深拷贝的知识,不知道为什么会报错,我用的深拷贝方法,看了好几遍我也没看出问题来。