overloading << operator to print all over a classes variables

I have a simple City class that holds a city name, pair of GPS coordinates, population and average temp. I am trying to overload the << operating so I can print out a cities details using cout << london.

Although I am getting the following static error: 'initialising': cannot convert from 'City*' to 'City'. Can anyone tell me why please?

Edit: it seems like this code will run in the compiler here, but I get this error in visual studio?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  using namespace std;
#include <utility> 
#include <iostream>

class City
{
private:
	string name;
	pair<double, double> cityCoords;
	int population;
	double tempAvg;
public:
	City(string, pair<double, double>, int, double);

	string getName();
	pair<double, double> getCityCoords();
	int getPopulation();
	double getTempAvg();

	friend ostream& operator<<(ostream&, City& c);
};


City::City(string n, pair<double, double> coords, int pop, double temp)
{
	name = n;
	cityCoords = coords;
	population = pop;
	tempAvg = temp;
}

string City::getName()
{
	return name;
}

pair<double, double> City::getCityCoords()
{
	return cityCoords;
}

int City::getPopulation()
{
	return population;
}

double City::getTempAvg()
{
	return tempAvg;
}

ostream& operator<<(ostream& out, City& c)
{
	    out << "City: " << c.getName() << "\nCoordinates: " << c.getCityCoords().first << ", " << c.getCityCoords().second << "\nPopulation: " << c.getPopulation() << "\nAverage Yearly Temp: " << c.getTempAvg();
		return out;
}

int main()
{
	pair<double, double> lon;
	lon.first = 41.06;
	lon.second = 105.45;

	City london = City("London", lon, 900000, 5.0);
	cout << london;
}
Last edited on
I am getting the following static error: 'initialising': cannot convert from 'City*' to 'City'.

Which line of the code?

(The code that you have posted does not produce such error.)
What is the compiler you are using?

Using MSVC (Visual Studio 2019) your code compiles and displays the output.
Microsoft Visual Studio Enterprise 2019
Version 16.4.2

strange..
Last edited on
never mind, my mistake. thanks for the replies guys
Topic archived. No new replies allowed.