c++ - 奇怪的输出 : why would this code give any meaningful output, 更不用说这个了?

标签 c++ templates operator-overloading cout generic-programming

我什至不确定如何陈述我的问题,但我们开始吧......

所以,我有这样一个 operator[] 有一个空主体(尚未实现)的类。不过,当我从 main() 调用它时,它会产生一个输出。更重要的是,输出正是上一行中分配给它的内容。

编辑:我添加了一个名为emptyValue 的私有(private)属性,并在类构造函数中将其初始化为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:

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

§1.3.24:

undefined behavior
behavior for which this International Standard imposes no requirements

关于c++ - 奇怪的输出 : why would this code give any meaningful output, 更不用说这个了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20787171/

相关文章:

c++ - 在 `unsigned char` 循环中遍历 `for` 的整个范围

c++ - 在 C++ 中从键盘完成 cin

c++ - 管道实现问题

c++ - 集合迭代器中的不完整类型

c++ - 如何参数化构造函数的参数个数?

c++ - 多重继承的麻烦。如何调用基函数?

c++ - 模板怪异

c++ - undefined reference : dll -> free function -> overloaded operator -> templated struct

c++ - 复杂表达式中重载 + 的问题

c++ - 复制构造函数和动态分配