[英]Objects not storing/retrieving correctly in vector (C++)
I'm a complete c++ beginner. 我是一个完整的C ++初学者。 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. 问题在于您有两件事叫做name
,并且您希望编译器弄清楚在name=name
,左侧是其中之一,而右侧是另一方。
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->
: 另一种选择是在成员访问this->
加上this->
:
terrainType::terrainType(string name, char symbol, int freq)
{
this->name=name;
this->symbol=symbol;
this->freq=freq;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.