#include<iostream> #include<cstring> using namespace std; class Dates{ public: Dates(int y=0,int m=0,int d=0):year(y),month(m),day(d){ } ~Dates(){ } int GetYear(){return year;} int GetMonth(){return month;} int GetDay(){return day;} private: //**********found********** int year; int month; int day; // 开花日期(年月日) }; //**********found********** class Plants: public Dates{ public: Plants(char*n,int y=0,int m=0,int d=0); ~Plants(); char*GetName(); private: char *name; // 植物名称 }; //**********found********** Plants::Plants(char*n,int y,int m,int d): date(y,m,d) { int length; length=strlen(n); name=new char[length+1]; strcpy(name,n); } Plants::~Plants() { delete []name; } char* Plants::GetName() { return name ; } bool IsEqual(Plants &pa,Plants &pb) // 判断pa和pb开花日期是否相同,是返回真,否则返回假 { if(pa.GetYear()==pb.GetYear()) //**********found********** if(pa.GetMonth()==pb.GetMonth()) if(pa.GetDay()==pb.GetDay())return true; return false; } int main() { Plants plantA("桃",2020,3,10); Plants plantB("杏",2020,4,5); cout<<plantA.GetName()<<"开花时间是:"<<plantA.GetYear()<<'-'<<plantA.GetMonth()<<'-'<<plantA.GetDay()<<endl; cout<<plantB.GetName()<<"开花时间是:"<<plantB.GetYear()<<'-'<<plantB.GetMonth()<<'-'<<plantB.GetDay()<<endl; if(IsEqual(plantA,plantB)) cout<<plantA.GetName()<<"和"<<plantB.GetName()<<"在同一天开花。"<<endl; else cout<<plantA.GetName()<<"和"<<plantB.GetName()<<"不在同一天开花。"<<endl; system("pause"); return 0; }代码错在哪
时间: 2023-07-23 20:21:27 浏览: 133
这段代码中有一个错误,即在植物类Plants的构造函数中,使用了未定义的变量date来初始化日期,应该改为使用父类Dates的构造函数来初始化日期,即:
```
Plants::Plants(char*n,int y,int m,int d): Dates(y,m,d) {
int length;
length=strlen(n);
name=new char[length+1];
strcpy(name,n);
}
```
另外,程序中没有必要使用动态内存分配来存储植物名称,可以改为使用字符数组来存储,即:
```
class Plants: public Dates{
public:
Plants(char*n="",int y=0,int m=0,int d=0);
~Plants();
char*GetName();
private:
char name[20]; // 植物名称
};
Plants::Plants(char*n,int y,int m,int d): Dates(y,m,d) {
strcpy(name,n);
}
Plants::~Plants() {
}
char* Plants::GetName() {
return name ;
}
```
这样可以更加简洁和安全地实现该程序。
相关问题
cstring转int
使用std::stoi函数可以将cstring转换为int,示例如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
char cstr[] = "123";
int i = stoi(cstr);
cout << i << endl; // 输出 123
return 0;
}
```
阅读全文
相关推荐














