简体   繁体   中英

Objects not storing/retrieving correctly in vector (C++)

I'm a complete c++ beginner. I'm trying to do a couple things that seem pretty basic: Create an object of a certain class, store it in a vector, then output a value of that object. At the moment it outputs a rectangle character, no matter what character I store. Here's the code:

#include <iostream>
#include <string>
#include <cstdlib>
#include <conio.h>
#include <time.h>
#include <windows.h> 
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

class terrainType
{
    public:
        string name;
        char symbol;
        int freq;
        terrainType(string,char,int);
};
terrainType::terrainType(string name, char symbol, int freq)
{
    name=name;
    symbol=symbol;
    freq=freq;
}

int main()
{
    vector<terrainType> terrainTypes;
    terrainType dirt("dirt",'.',1);
    terrainTypes.push_back(dirt);
    cout << terrainTypes[0].symbol;
    return 0;
}

Any advice or background info is appreciated. Thanks!

The three assignments you have in the constructor are effectively no-ops (you're assigning each variable to itself):

terrainType::terrainType(string name, char symbol, int freq)
{
    name=name;
    symbol=symbol;
    freq=freq;
}

The issue is that you have two things called name , and you expect the compiler to figure out that in name=name the left-hand side refers to one of them, whereas the right-hand side refers to the other.

The cleanest way to fix this is by changing to constructor like so:

terrainType::terrainType(string name, char symbol, int freq)
: name(name),
  symbol(symbol),
  freq(freq)
{
}

The rules of the language are such that this would have the intended meaning.

Another alternative is to avoid using the same identifier to refer to both a member and a function argument:

terrainType::terrainType(string name_, char symbol_, int freq_)
{
    name=name_;
    symbol=symbol_;
    freq=freq_;
}

Yet another alternative is to prefix member access with this-> :

terrainType::terrainType(string name, char symbol, int freq)
{
    this->name=name;
    this->symbol=symbol;
    this->freq=freq;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM