怪异的输出:为什么这段代码会给出任何有意义的输出,更不用说这个了
Freaky output: why would this code give any meaningful output, let alone this?
我什至不知道如何陈述我的问题,但我们开始了......
所以,我有这个类,operator[]
有一个空的主体(尚未实现)。不过,当我从 main()
调用它时,它会产生一个输出。更重要的是,输出正是在上一行中分配给它的内容。
EDIT
:我添加了一个名为 emptyValue
的私有属性,并将其初始化为在类构造函数中TipVrijednosti()
。
下面是示例:
template<typename TipKljuca, typename TipVrijednosti>
class BinStabloMapa : public Mapa<TipKljuca, TipVrijednosti>
{
.
.
TipVrijednosti &operator[] (const TipKljuca &kljuc) {
return emptyValue;
}
const TipVrijednosti &operator[] (const TipKljuca &kljuc) const {
return emptyValue;
}
.
.
}
int main()
{
BinStabloMapa<int, int> m;
m[100] = 200;
cout << m[100] << endl;
return 0;
}
OUTPUT: 200
谁能告诉我为什么会这样?
您有未定义的行为,因为您没有从具有非void
返回类型的函数返回任何内容。
§6.6.3:
从函数末尾流出等效于没有值的返回;这会导致值返回函数中出现未定义的行为。
§1.3.24:
未定义的行为
本标准未提出要求的行为
不是那么大的难题。 您的operator []
返回对名为 emptyValue
的某个数据变量的引用。
m[100] = 200;
等效于
m.emptyValue = 200;
然后你写 cout <<m[100];
这就像
cout << m.emptyValue;
注意:索引"100"无关紧要。
这没什么:
#include <iostream>
using namespace std;
template<typename TipKljuca, typename TipVrijednosti>
class BinStabloMapa /* : public Mapa<TipKljuca, TipVrijednosti> */
//comment inheritance to make it compile, not relevant to the problem
{
//C++11 syntax, not relevant either
TipVrijednosti emptyValue=TipVrijednosti();
public:
TipVrijednosti &operator[] (const TipKljuca &kljuc) {
return emptyValue;
}
const TipVrijednosti &operator[] (const TipKljuca &kljuc) const {
return emptyValue;
}
};
int main()
{
BinStabloMapa<int, int> m;
m[100] = 200; //calls no const operator[], thus emptyValue is changed
cout << m[100] << endl; //calls const operator[], thus emptyValue is return
return 0;
}
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 代码编译没有任何输出,入门程序
- 可能我知道为什么这段代码没有给出任何输出吗?
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- 为什么下面的Hello World程序在PowerShell上没有显示任何输出?同一程序在CMD上显示正确的输出
- 执行此代码时,它不显示任何输出.为什么?
- 合并排序没有给我任何输出
- 编译器没有显示错误,但我没有得到任何输出.怎么了?
- 是给定代码中的任何更改,以便我可以为问题提供正确的输出
- 为什么我的代码在终端中没有输出任何内容.开始新行没有错误
- 无法输出任何内容
- 为什么这个程序不输出任何东西
- 函数不会从向量输出任何内容C++
- 提升 BCP 不输出任何文件?
- 按回车键后,程序没有输出任何结果.为什么会这样
- 任何 c++ 程序都不会输出任何内容
- 程序从不输出任何输出
- 为什么程序开头的cout语句没有输出任何东西?
- 为什么这个openGL代码没有输出任何东西
- 为什么signalhandler不输出任何东西?