【发布时间】:2020-12-24 13:14:07
【问题描述】:
我正在学习面向对象编程的概念
从动态内存分配入手,发现这段代码有问题。 我在这段代码中找不到问题,在我看来一切都很好
#include <iostream>
using namespace std;
class Team
{
private:
char *name;
char stadium[20];
char city[20];
public:
Team(const char *i=" ",const char *stadium=" ",const char *city=" ")
{
name=new char [strlen(i)];
strcpy(name,i);
strcpy(this->stadium,stadium);
strcpy(this->city,city);
}
const char *getName() {
return name;
}
const char *getCity() {
return city;
}
const char *getStadium() {
return stadium;
}
void setName(char *name) {
strcpy(this->name, name);
}
~Team() {
delite [] name;
}
};
};
int main()
{
Team *e1 = new Team("Real Madrid", "Madrid", "Santiago Bernabeu");
Team *e2 = new Team(*e1);
cout << e1->getName();
cout << "-";
cout << e2->getName();
e1->setName("Barselona");
cout << e1->getName();
cout << "-";
cout << e2->getName();
delete e1;
delete e2;
return 0;
}
我希望解决这个问题超过 3 个小时......但没有找到任何东西,我知道这可能不是我需要寻找解决方案的方式。但我厌倦了试图解决这个问题。
我遇到的一些错误
main.cpp: In constructor ‘Team::Team(const char*, const char*, const char*)’:
main.cpp:13:24: error: ‘strlen’ was not declared in this scope
name=new char [strlen(*i)];
^~~~~~
main.cpp:13:24: note: suggested alternative: ‘mbrlen’
name=new char [strlen(*i)];
^~~~~~
mbrlen
main.cpp:14:9: error: ‘strcpy’ was not declared in this scope
strcpy(name,i);
^~~~~~
main.cpp:14:9: note: suggested alternative: ‘strtoq’
strcpy(name,i);
^~~~~~
strtoq
我试过这段代码
#include<iostream>
#include<cstring>
using namespace std;
class Team {
private:
char *name;
char city[20];
char stadion[30];
public:
Team(char *name = "", char *city = "", char *stadion = "") {
this->name = new char[20];
strcpy(this->name, name);
strcpy(this->city, city);
strcpy(this->stadion, stadion);
}
Team(const Team &e) {
strcpy(name, e.name);
strcpy(city, e.city);
strcpy(stadion, e.stadion);
}
const char *getName() {
return name;
}
const char *getCity() {
return city;
}
const char *getStadion() {
return stadion;
}
void setName(char *name) {
strcpy(this->name, name);
}
~Team() {
// delite [] name;
}
};
int main() {
Team *e1 = new Team("Real Madrid", "Madrid", "Santiago Bernabeu");
Team *e2 = new Team(*e1);
cout << e1->getName();
cout << "-";
cout << e2->getName();
e1->setName("Barselona");
cout << e1->getName();
cout << "-";
cout << e2->getName();
delete e1;
delete e2;
return 0;
}
得到这个错误
main.cpp:44:26: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
Segmentation fault (core dumped)
【问题讨论】:
-
您能否添加错误消息以及您尝试过的一些信息?
-
我现在会编辑帖子,不用担心:)
-
std::string有什么问题?如果您坚持为字符串手动分配内存,请注意strlen(i)(不是strlen(*i))不包括空终止符。delite [] name;也不是有效的 C++ -
已修复但仍无法正常工作,问题是我正在使用动态分配的参数在动态内存中创建对象吗?
标签: c++ oop dynamic-memory-allocation