【问题标题】:How do I store strings (or any type) into an array of type T?如何将字符串(或任何类型)存储到 T 类型的数组中?
【发布时间】:2020-02-29 19:26:17
【问题描述】:

我试图在 T 类型的数组中存储一个字符串(或任何类型),但出现两个错误:

“std::string &”类型的引用(非 const 限定)不能 用“const char [3]”类型的值初始化

'bool container::insertBack(T &)': 无法转换 参数 1 从 'const char [3]' 到 'T &'

我尝试将类型更改为 int 而不是 string:我收到了类似的错误消息。

#include <iostream>
#include <string>

template<typename T>
class container
{
public:
    container();
    // Postcondition: data member n is initialized to -1 and all elements in the empty arr array are initialized to zero
    bool isFull();
    // Postcondition: returns true if the container object (i.e., the arr array) is full; returns false otherwise
    bool insertBack(T& val);
    //  Precondition: the container object is not full
    // Postcondition: if arr array is not full, n is incremented by 1; returns true with val is inserted at the end of the arr array 
    //                 Otherwise, returns false; the value is not inserted and program execution continues.
private:
    static const int CAPACITY = 10;     // physical size of the arr array or the storage capacity of a container object
    T arr[CAPACITY];            // arr array can store up to CAPACITY  (10 in our case) of any type 
    int n;                      // n is used as the subscript for the arr array. n is initialized to -1 for an empty array
                                // Each time a new value is inserted into the arr array, n must first be incremented 
                                // by 1. Since n has been initialized to -1, the first inserted value is stored in arr[0],
                                // and the 2nd inserted value will be in arr[1], etc.  and the nth inserted value will be 
                                // stored in arr[n – 1]. Obviously, n + 1 represents the actual number of elements
                                // stored in the array after n rounds of insertion.         
};

template<typename T>
container<T>::container()
{
    n = -1;
    T arr[CAPACITY] = { 0 };
}

template<typename T>
bool container<T>::isFull()
{
    return n == CAPACITY - 1;
}

template<typename T>
bool container<T>::insertBack(T& val)
{
    if (!isFull())
    {
        n++;
        arr[n - 1] = val;
        return 1;
    }
    else
    {
        return 0;
    }
}

int main()
{
    container<std::string> s1;
    s1.insertBack("aa");
}

【问题讨论】:

  • 您的bool insertBack(T&amp; val); 需要引用T(即std::string),但您提供的是字符串文字,而不是std::string。您可以将其更改为 bool insertBack(T const&amp; val) 以允许任何可转换为 std::string 的内容。
  • (请注意,你还没有走出困境,但至少这会让你的代码编译好,这样你就可以开始调试了。)
  • @RaymondChen 有点困惑 > 你提供的是字符串文字,而不是 std::string;两者之间有区别吗:我一直认为它们是相同的
  • 它们非常不同。即使它们相同,您的代码仍然无法编译,因为 T&amp; 需要一个左值引用,但您传递的是一个值,而不是变量名。
  • @S.Coughing 字符串文字的类型为const char[N],在大多数情况下衰减为const char*std::string 与字符串文字没有任何共同之处,只是它提供了一个构造函数std::string(const char*),这使得它可以从字符串文字隐式转换。

标签: c++ arrays templates


【解决方案1】:

g++ 针对相同的错误给出稍微不同的输出:

cannot bind non-const lvalue reference of type 'std::__cxx11::basic_string&lt;char&gt;&amp;' to an rvalue of type 'std::__cxx11::basic_string&lt;char&gt;'

clang++:

non-const lvalue reference to type 'std::__cxx11::basic_string&lt;char&gt;' cannot bind to a value of unrelated type 'const char [3]'

解决方案是将参数作为const&amp;

接下来你会发现 T arr[CAPACITY] = { 0 };
给出一个运行时异常,如: basic_string::_M_construct null not valid.

你不是像那样零初始化arr。实际上,您正在创建一个新的arr 并尝试使用nullptr 构造它,这对于std::string[] 不起作用。

您不妨使用像 size_t 这样的无符号整数来计算元素,就像标准容器所做的那样,以便将来与标准函数/算法的交互更容易。

有了固定的::

#include <iostream>
#include <string>

template<typename T, size_t Capacity = 10>       // made the capacity selectable
class container {
public:
    container() : arr{}, n(0) {}                 // using member initializer list

    bool isFull() const { return n == Capacity; } // correct test with a 0 based counter

    bool insertBack(const T& val) {               // const
        if (isFull()) return false;
        // return true or false, not 1 or 0 
        arr[n++] = val;
        return true;
    }

private:
    T arr[Capacity];
    size_t n;
};

int main() {
    container<std::string> s1;
    s1.insertBack("aa");
}

【讨论】:

    猜你喜欢
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多