#include<iostream> using namespace std; class CPerson{ protected: long id; char* name; int age; public: CPerson(long i,char* n,int a):id(i),name(n),age(a){ } CPerson(){ } CPerson(const CPerson &C){ id=C.id; name=C.name; age=C.age; } ~CPerson(){ delete name; } void set(){ cout<<"ID:"; cin>>id; cout<<"NAME:"; cin>>name; cout<<"AGE:"; cin>>age; } void display(){ cout<<"id:"<<id<<" name:"<<name<<" age:"<<age<<endl; } }; int main(){ CPerson obj1(1002,"LiMing",22); obj1.display(); CPerson obj2(obj1); obj2.set(); obj2.display(); return 0; }为什么警告
时间: 2023-12-03 17:44:12 浏览: 63
在这段代码中,有两个问题会导致警告:
1. 字符串指针未初始化。在类中,使用 `char*` 类型的字符串指针作为成员变量,需要在构造函数中对其进行初始化,否则会导致未定义的行为。可以使用动态内存分配来初始化字符串指针,例如 `name = new char[20];`。
2. 拷贝构造函数未正确实现。在拷贝构造函数中,需要将字符串指针所指向的内存空间也进行拷贝,而不仅仅是拷贝指针本身。可以使用 `strcpy()` 函数来实现字符串指针的拷贝,例如 `strcpy(name, C.name);`。同时,需要注意对字符串指针进行内存分配和释放。
修复后的代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
class CPerson {
protected:
long id;
char* name;
int age;
public:
CPerson(long i, char* n, int a) : id(i), age(a) {
name = new char[strlen(n) + 1];
strcpy(name, n);
}
CPerson() {
id = 0;
name = new char[1];
name[0] = '\0';
age = 0;
}
CPerson(const CPerson& C) {
id = C.id;
age = C.age;
name = new char[strlen(C.name) + 1];
strcpy(name, C.name);
}
~CPerson() {
delete[] name;
}
void set() {
cout << "ID:";
cin >> id;
cout << "NAME:";
char tmp[20];
cin >> tmp;
if (name != nullptr) {
delete[] name;
}
name = new char[strlen(tmp) + 1];
strcpy(name, tmp);
cout << "AGE:";
cin >> age;
}
void display() {
cout << "id:" << id << " name:" << name << " age:" << age << endl;
}
};
int main() {
CPerson obj1(1002, "LiMing", 22);
obj1.display();
CPerson obj2(obj1);
obj2.set();
obj2.display();
return 0;
}
```
阅读全文