【问题标题】:Why is this C++ array template class initialized with garbage values? [closed]为什么这个 C++ 数组模板类用垃圾值初始化? [关闭]
【发布时间】:2021-03-19 18:00:39
【问题描述】:

使用 Visual Studio 2019,我正在尝试创建一个模板数组类,其中 T 是数组的类型,S 是它的大小:

// Array.hpp
#include <iostream>
template<typename T, int S> class Array {

    T m_array[S];
    
public:

    Array() : Array(0) {}

    Array(const T& val) {
        for (int i = 0; i < S; i++) { m_array[i] = val; }
    }

    template<typename E> Array(const E& val) {
        for (int i = 0; i < S; i++) { m_array[i] = static_cast<T>(val); }
    }

    int size() const { return S; }
    T operator[](int position) const { return m_array[position]; }
    T& operator[](int position) { return m_array[position]; }

    friend std::ostream& operator<<(std::ostream& os, const Array& a) {
        os << '[';
        if (a.size() > 0) { os << a[0]; }
        for (int i = 1; i < a.size(); i++) {
            os << ', ' << a[i];
        }
        return os << ']';
    }
};

但是,当我创建 Array 的对象并打印它时,我发现输出中混入了奇怪的值:

// main.cpp
#include "Array.hpp"

using namespace std;

int main()
{
    Array<int, 10> a1(3);
    Array<double, 10> a2(3.14);
    Array<int, 10> a3(5.9);

    cout << a1 << endl;
    cout << a2 << endl;
    cout << a3 << endl;
}

给我这个输出:

【问题讨论】:

  • 请不要将文字作为图片发布。
  • ', ' -> ", "

标签: c++ visual-studio templates


【解决方案1】:

这个:

', '

是一个多字符文字。这根本不是你想要的。替换为:

", "

如果可以,请在编译器中针对多字符文字打开警告。在 GCC 中是 -Wmultichar

【讨论】:

    猜你喜欢
    • 2021-09-02
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 2021-01-15
    • 2020-07-23
    • 1970-01-01
    相关资源
    最近更新 更多