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