深拷贝于浅拷贝的问题
以下代码哪里出现了问题编译出来提示const char to char
#include<iostream>
#include<string>
using namespace std;
class Person
{
public:
Person(int age ,char name)
{
m_age = age;
m_name = new char(name);
cout << "Person的构造函" << endl;
}
//Person(const Person& p)
//{
//cout << "拷贝构造函数" << endl;
//m_age = p.m_age;
// m_height = new int(*p.m_height);
//}
~Person()
{
if(m_name != NULL)
{
delete m_name;
m_name = NULL;
}
cout << "Person的析构函数" << endl;
}
int m_age;
char *m_name;
};
void test1()
{
Person p1(18 , "zy");
cout << "年龄:" << p1.m_age << "名字:" << *p1.m_name <<endl;
Person p2(p1);
cout << "年龄" << p2.m_age << "名字:" << *p2.m_name << endl;
}
int main(int argc , char **argv)
{
test1();
return 0;
} #include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Person {
public:
// Person(int age ,char name)
Person(int age, const char *name) {
m_age = age;
// m_name = new char(name);
m_name = new char;
m_name = '\0'; strcpy(m_name, name);
cout << "Person的构造函" << endl;
}
//Person(const Person& p)
//{
//cout << "拷贝构造函数" << endl;
//m_age = p.m_age;
// m_height = new int(*p.m_height);
//}
Person(const Person &rhs) {
m_age = rhs.m_age;
m_name = new char;
m_name = '\0'; strcpy(m_name, rhs.m_name);
}
~Person() {
if(m_name != NULL) {
//delete m_name;
delete[] m_name;
m_name = NULL;
}
cout << "Person的析构函数" << endl;
}
int m_age;
char *m_name;
};
void test1() {
Person p1(18, "zy");
//cout << "年龄:" << p1.m_age << "名字:" << *p1.m_name << endl;
cout << "年龄:" << p1.m_age << "名字:" << p1.m_name << endl;
Person p2(p1);
//cout << "年龄" << p2.m_age << "名字:" << *p2.m_name << endl;
cout << "年龄" << p2.m_age << "名字:" << p2.m_name << endl;
}
int main(int argc, char **argv) {
test1();
return 0;
}
页:
[1]