Understanding structures

Okay so I'm starting to practice using structures and I can't figure out why the following code will not work. To my understanding a structure can be treated as a type similar to type int, but whenever I try to declare it as a type in main it returns a "no matching function call". I'm trying to input values and output them using the structured content inside of mountain. Does anybody know why this is happening?

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

#include <cstdio>
#include <cstddef>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>


using namespace std;


struct mountains
{
    char* name;
    int elevations;


    mountains(int elevation)
    {
        elevations = 0;
    }

};


int main(int argc, char** argv)
{
    mountains mtnName, mtnElevation;

    cin >> mtnName.name;
    cin >> mtnElevation.elevations;

    cout << mtnName.name;
    cout << mtnElevation.elevations;

    return 0;
}
Last edited on
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
#include <iostream>
#include <string>

struct mountain
{
    std::string name ;
    int elevation ;

    // constructor: initialise members name and elevation
    // http://en.cppreference.com/w/cpp/language/initializer_list
    explicit mountain( std::string nam, int elev ) : name(nam), elevation(elev) {}
};

int main()
{
    std::string name ;
    std::cout << "name of mountain? " ;
    std::cin >> name ;

    int elevation ;
    std::cout << "elevation in metres? " ;
    std::cin >> elevation ;

    mountain mtn( name, elevation ) ; // create object mtn (invokes the constructor)

    // print out the value of the members
    std::cout << "\n\nname: " << mtn.name << "  elevation: " << mtn.elevation << " metres\n";
}

http://coliru.stacked-crooked.com/a/3f4083307c8653d6
Take note of what JLBorges wrote.

To answer your question yes you can treat a struct as an int type. But the "type" is the name of the struct so in your case the type is mountain.

In JLBorges example in line 24 he instantiates an object of type Mountain and calls it mtn and passes in the name and elevation parameters.

Hope that helps. Feel free to ask anymore questions to help clarify!
Topic archived. No new replies allowed.