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

时间:2012-04-28 20:47:56

标签: c++ object vector

我是一个完整的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;
}

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

1 个答案:

答案 0 :(得分:5)

构造函数中的三个赋值实际上是无操作(您将每个变量赋值给自己):

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

问题在于你有两个名为name的东西,你希望编译器在name=name中找出左侧是指其中一个,而右侧是指的是另一个。

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

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

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

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

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

另一种选择是使用this->

为成员访问加前缀
terrainType::terrainType(string name, char symbol, int freq)
{
    this->name=name;
    this->symbol=symbol;
    this->freq=freq;
}
相关问题