|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
“编写一个完整的城市类,并利用该类定义自己家乡为一个具体对象,并在主函数中展示城市的具体信息”
萌新想问下这个程序哪里错了呀,不知道该怎么改,谢谢大佬们
#include<iostream>
#include<string.h>
using namespace std;
class City{
public:
char m_name[100],m_location[100],m_weather[100];
City(char*name,char*location,char*weather){
strcpy((char*)m_name,(char*)name);
strcpy((char*)m_location,(char*)location);
strcpy((char*)m_weather,(char*)weather);
}
void getname(){
cout<<m_name;
}
void getlocation(){
cout<<m_location;
}
void getweather(){
cout<<m_weather;
}
};
int main()
{
City name("Yixing");
name.getname();
City location("It locates in the south of Jiangsu province.");
location.getlocation();
City weather("wet");
weather.getweather();
system("pause");
return 0;
}
给你写了一个C++风格的:
- #include <iostream>
- //#include<String.h>
- #include <string> //C++的string 类,比C语言的字符数组表示的字符串好用
- using namespace std;
- class City
- {
- public:
- // 构造函数
- City(){}; //默认构造函数,可以不写,也可以在函数体中给成员变量默认值
- City(const string name, const string location, const string weather) : m_name(name), m_location(location), m_weather(weather) // 初始化列表形式的成员变量初始化。当然你也可以采用下面注释掉的赋值方式。
- {
- // this->m_name = name;
- // this->m_location = location;
- // this->m_weather = weather;
- }
- //成员函数
- // 设置名称
- void setname(const string name)
- {
- this->m_name = name; //C++ string类中有=运算符,以及一些非常方便的字符串操作函数,应用起来更加方便
- }
- // 设置位置
- void setlocation(const string loc)
- {
- this->m_location = loc;
- }
- // 设置气候
- void setweather(const string weather)
- {
- this->m_weather = weather;
- }
- // 成员变量读取函数
- string getname()
- {
- return this->m_name;
- }
- string getlocation()
- {
- return this->m_location;
- }
- string getweather()
- {
- return this->m_weather;
- }
- void printInfo() // 打印城市信息。
- {
- cout << "Name: "<< this->m_name << endl;
- cout << "Location: " << this->m_location << endl;
- cout << "Weather: " << this->m_weather << endl;
- }
- //成员变量声明
- private: // 为了数据安全,一般情况下成员变量以私有变量形式出现。成员变量的访问只能通过定义好的成员函数进行。
- string m_name;
- string m_location;
- string m_weather;
- };
- int main()
- {
- // 声明一个City类的对象并初始化化
- City myCity("Yixing", "It lcates in the south of Jiangsu province", "Wet");
- // 打印对象myCity的城市信息
- myCity.printInfo(); //调用成员函数
- cout << myCity.getname() << myCity.getlocation() << myCity.getweather() << endl; //采用cout,调用成员变量读取函数
-
- //更新城市信息。
- myCity.setname("Xi'an");
- myCity.setlocation("Locates in the central part of Shaanxi province");
- myCity.setweather("Moderate");
- // 打印城市信息
- myCity.printInfo();
- City anotherCity; //这里会调用默认构造函数,由于我写的默认构造函数体是空的,所以成员变量没有赋值
- anotherCity.printInfo();// 由于成员变量没有初始化,所以打印出来应该是所有变量都是空字符串
- anotherCity.setname("Beijing"); //设置对象anotherCity的m_name;
- anotherCity.printInfo(); //打印城市信息,可以看到名字已经被更新
- system("pause");
- return 0;
- }
复制代码
|
|