编辑
好的,我又读了几个小时,现在我终于更好地理解了C++面向对象编程(至少是基础)。我决定重新编写整个程序,逐步编写代码并进行更多测试。我觉得这次我把错误缩小了一些。
NamedStorm.h
#include <string>
#include <iostream>
#ifndef NAMEDSTORM_H_INCLUDED
#define NAMEDSTORM_H_INCLUDED
// NEVER use using namespce in header, use std instead.
class NamedStorm{
private:
std::string stormName;
std::string stormCategory;
double maxWindSpeed;
double stormPressure;
static int stormCount;
public:
// Constructor
NamedStorm(std::string, double, std::string, double);
NamedStorm(std::string);
// Destructor
~NamedStorm();
// Get functions
int getStormCount();
double getStormPressure();
double getWindSpeed();
std::string getStormCategory();
std::string getName();
// Set functions
static void displayOutput();
static void sortByNames();
static void sortByWindSpeed();
static void getAverageWindSpeed();
static void getAverageStormPressure();
};
#endif // NAMEDSTORM_H_INCLUDED
NamedStorm.cpp
// CPP => Function definition
#include <string>
#include "NamedStorm.h"
using namespace std;
// Defining static variables
int NamedStorm::stormCount = 0;
// Constructor definition
NamedStorm::NamedStorm(std::string sName, double wSpeed, std::string sCat, double sPress){
stormName = sName;
windSpeed = wSpeed;
stormCategory = sCat;
stormPressure = sPress;
stormCount++;
}
NamedStorm::NamedStorm(std::string sName){
stormName = sName;
stormCount++;
}
// Destructor definition
NamedStorm::~NamedStorm(){}
// Get (Accessor) function definition
int NamedStorm::getStormCount(){
return stormCount;
}
double NamedStorm::getStormPressure(){
return stormPressure;
}
string NamedStorm::getStormCategory(){
return stormCategory;
}
string NamedStorm::getName(){
return stormName;
}
// Set (Mutator) function definition
void NamedStorm::displayOutput(){}
void NamedStorm::sortByNames(){}
void NamedStorm::getAverageStormPressure(){}
void NamedStorm::getAverageWindSpeed(){}
void NamedStorm::getWindSpeed(){}
main.cpp
#include <iostream>
#include <string>
#include "NamedStorm.h"
using namespace std;
NamedStorm storm[5]; // Error occurs here
int main(){
// NamedStorm Chris("Chris", 70.0, "T.S", 990.0);
// storm[0] = Chris;
return 0;
}
NamedStorm(){};
不仅是声明,也是定义。笔误? - dypusing namespace blah;
。 - chrisusing namespace std
。 - juanchopanzadisplayOutput
函数有一个 bug。使用std::array
,它知道自己的大小,并且你可以像在 Java 中一样用任意数组一次性初始化对象。 - chris