没有在向量中正确存储/检索的对象(C++)

Aus*_*ten 1 c++ vector object

我是一个完整的c ++初学者.我正在尝试做一些看似非常基本的事情:创建某个类的对象,将其存储在向量中,然后输出该对象的值.目前它输出一个矩形字符,无论我存储什么字符.这是代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

任何建议或背景信息表示赞赏.谢谢!

NPE*_*NPE 5

您在构造函数中拥有的三个赋值实际上是无操作(您将每个变量分配给自身):

terrainType::terrainType(string name, char symbol, int freq)
{
    name=name;
    symbol=symbol;
    freq=freq;
}
Run Code Online (Sandbox Code Playgroud)

问题是你有两个东西被调用name,你希望编译器弄清楚name=name左边是指其中一个,而右边是指另一个.

解决这个问题的最简单方法是更改​​为构造函数,如下所示:

terrainType::terrainType(string name, char symbol, int freq)
: name(name),
  symbol(symbol),
  freq(freq)
{
}
Run Code Online (Sandbox Code Playgroud)

语言的规则是这样的,它具有预期的含义.

另一种方法是避免使用相同的标识符来引用成员和函数参数:

terrainType::terrainType(string name_, char symbol_, int freq_)
{
    name=name_;
    symbol=symbol_;
    freq=freq_;
}
Run Code Online (Sandbox Code Playgroud)

然而,另一种选择是前缀的成员访问有this->:

terrainType::terrainType(string name, char symbol, int freq)
{
    this->name=name;
    this->symbol=symbol;
    this->freq=freq;
}
Run Code Online (Sandbox Code Playgroud)