初始化C++中的对象向量

Initialize a vector of objects in C++

本文关键字:对象 向量 C++ 初始化      更新时间:2023-10-16

我的问题是:我有一个名为 City 的类,其中包含参数名称、纬度和经度。在我的主课中,我想初始化一些城市的向量。

这是我的城市头文件:

using namespace std;
#define RADIUS 6378.137
#define PI 3.14159265358979323846

class City {
public:
City(string _name, double _latitude, double _longitude) {
name = _name;
longitude = _longitude * PI / 180.0;
latitude = _latitude * PI / 180.0;
}
~City() { };
private:
double longitude;
double latitude;
string name;
double earthRadius = RADIUS;
};

然后是我的主类文件:

#include <iostream>
#include <vector>
#include "Route.h"
using namespace std;
vector<City> initRoute { (("Boston", 42.3601, -71.0589),
("Houston", 29.7604, -95.3698), ("Austin", 30.2672, -97.7431),
("San Francisco", 37.7749, -122.4194), ("Denver", 39.7392, -104.9903),
("Los Angeles", 34.0522, -118.2437), ("Chicago", 41.8781, -87.6298)) };
int main() {
//for each(City city in initRoute)
//city.printCity;
system("pause");
return 0;
}

当我尝试编译时,它会发出错误 C2398:

Error   C2398   Element "1": Die Conversion from "double" to  "unsigned int" 
requires a restrictive conversion.

我感觉我的向量初始化是错误的,但我不知道该改变什么。

感谢您的帮助:)

在将对象添加到vector时,必须指定对象的类型。

vector<City> initRoute { City("Boston", 42.3601, -71.0589),
City("Houston", 29.7604, -95.3698), ... };

您可以使用{}来表示对象,而无需显式提及类,因为您的向量包含City对象(就像您使用structs 一样(。

vector<City> initRoute { {"Boston", 42.3601, -71.0589},
{"Houston", 29.7604, -95.3698}, ... };