【发布时间】:2019-12-29 04:04:53
【问题描述】:
c++中有一个模板类:
#include <iostream>
#include <vector>
using std::ostream;
using std::vector;
template<typename T>
class Business {
public:
// default constructor
Business() {
customers.push_back(0);
}
// value constructor
Business(vector<T> vec) {
for (int i = 0; i < vec.size(); ++i)
customers.push_back(vec[i]);
}
T getInfo(int i) const {
if (i < 0 ) return 0;
else return customers[i];
}
friend ostream &operator<<(ostream &os, const Business<T> &b) {
std::string message = "";
for (int i=0 ; i<b.customers.size() ; ++i) {
message += b.getInfo(i) + " ";
}
return os << message;
}
private:
vector<T> customers;
};
但我收到以下关于 operator<< 正文的错误:
error: invalid operands to binary expression: message += b.getInfo(i) + " ";
收到该错误后,我将容易出错的代码行更改为:
message += b.getInfo(i)
然后错误是:
error: no viable overloaded '+=': message += b.getInfo(i)
编辑: 我有一个主要课程:
Business<Merchant<95>> bu({45, 87, 95, 23});
std::cout << bu << endl;
其中Merchant<95> 是另一个模板类。
我收到的错误如下:
in instantiation of member function 'operator<<' requested here: cout << bu << endl;
不知道怎么解决?
谢谢。
【问题讨论】:
-
std::string的+=运算符仅适用于其他字符串。如果T不是std::string或可以隐式转换为std::string的东西,您应该会收到这样的消息。 -
目前我可能误诊了。我目前无法重现您的问题。
-
我需要了解更多你在做什么。要获得报告的错误消息,还应该有一些其他的错误消息。我也忘记了
+=可以接受chars 并且整数数据类型可以隐式转换为chars。在这种情况下没有错误消息,只是一个错误的答案。你能用minimal reproducible example 更新问题吗(假设minimal reproducible example 不会导致“D'oh!”时刻并且你修复了错误)? -
我还是看错了。一个整数加上一个字符串文字将是指针算术偏移到该字符串文字。示例:ideone.com/iCsUEX。
"ABC"是const char[4]。它衰减到const char *,即内存中"ABC"的地址。如果你在那个地址上加 1,你基本上就有一个字符串“BC”。但现在我正徘徊在喋喋不休的土地上。我想我应该停下来过夜。 -
关键是标准类型。
Merchant,不管它是什么,都不是标准的。除非您有将int0 转换为Merchant的方法,否则if (i < 0 ) return 0;也应该有问题。我们还需要更多。请阅读minimal reproducible example 了解我们需要的更多信息。
标签: c++