【发布时间】:2018-11-23 17:46:51
【问题描述】:
Pairwise 类表示具有键:值的对。我制作了一个模板对,但在尝试使用类的键和值输入运行并将其打印出来时出错。
鉴于我的主要:
#include "file_name.h"
int main (){
Pairwise<string, string> example = {{"key", "value"}};
cout << example << endl;
}
还有我的头文件:
#pragma once
#include<iostream>
using std::ostream; using std::cout; using std::endl;
#include<string>
using std::string;
#include<utility>
using std::pair;
#include<sstream>
using std::ostringstream;
template<typename K, typename V>
struct Pairwise{
K first;
V second;
Pairwise() = default;
Pairwise(K, V);
//print out as a string in main
friend ostream& operator<<(ostream &out, const Pairwise &n) {
ostream oss;
string s;
oss << n.first + ":" + n.second; //possible error?
s = oss.str();
out << s;
return out;
}
};
运行 main 后我的预期输出是:
key:value
但是,我收到了错误:
h:28:11: error: 'std::basic_ostream<_CharT, _Traits> is protected within..."
【问题讨论】:
-
那个流插入器有点复杂。
out << n.first << ":" << n.second; return out;就足够了。事实上,我只想把它写成单行:return out << n.first << ':' << n.second;,但有些人喜欢更冗长。 -
ostream oss;是一个错字,对吧?应该是ostringstream oss;。并且错误消息被截断。不要总结;发布您能想出的显示问题的最小代码,并引用整个错误消息。这里没有任何受保护的东西,所以错误消息的那部分需要上下文才能有意义。 -
除了不必要的复杂...
oss << n.first + ":" + n.second;– 为什么+?这将其功能限制为支持+本身和字符串文字的类型。 -
@PeteBecker 很棒,缩短的代码总是对我有帮助!
-
@Swordfish 感谢您指出“+”运算符。我一直在寻找改进代码的方法。你认为我的主要功能看起来还不错吗?将值传递给模板类