一个最令人头疼的解析案例
A case od the most vexing parse
我的代码一直报错Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'const bus')
这是最麻烦的解析案例吗?如果是这样如何解决它。我正在尝试打印出存储在向量中的对象。 std::vector<bus> v = {}
是我包含对象的向量,而 bus
是我的 class
#include <iostream>
#include <vector>
class bus{
public:
int carNum, releaseYear;
};
int temp1, temp2;
void print(std::vector<bus> const &input)
{
for (auto it = input.cbegin(); it != input.cend(); it++)
{
std::cout << *it << ' '<< std::endl;
}
}
int main()
{
bus bus1;
bus1.carNum = 0;
bus1.releaseYear = 0;
bus bus2;
bus2.carNum = 0;
bus2.releaseYear = 0;
// Create a vector containing objects
std::vector<bus> v = {};
// Add two more integers to vector
std::cout<<"enter number"<<std::endl;
std::cin>>temp1;
temp1 = bus1.carNum;
std::cout<<"enter year"<<std::endl;
std::cin>>temp2;
temp2 = bus1.releaseYear;
v.push_back(bus1);
print(v)
}
这里没有令人烦恼的解析。您只需为 bus
类型重载流插入运算符。由于 bus
只有 public 数据成员,这可以是一个非友元函数:
std::ostream& operator<<(std::ostream& stream, bus const& b)
{
stream << "#" << b.carNum << " Year" << b.releaseYear;
return stream;
}
您当然可以根据需要格式化输出。
我的代码一直报错Invalid operands to binary expression ('std::__1::ostream' (aka 'basic_ostream<char>') and 'const bus')
这是最麻烦的解析案例吗?如果是这样如何解决它。我正在尝试打印出存储在向量中的对象。 std::vector<bus> v = {}
是我包含对象的向量,而 bus
是我的 class
#include <iostream>
#include <vector>
class bus{
public:
int carNum, releaseYear;
};
int temp1, temp2;
void print(std::vector<bus> const &input)
{
for (auto it = input.cbegin(); it != input.cend(); it++)
{
std::cout << *it << ' '<< std::endl;
}
}
int main()
{
bus bus1;
bus1.carNum = 0;
bus1.releaseYear = 0;
bus bus2;
bus2.carNum = 0;
bus2.releaseYear = 0;
// Create a vector containing objects
std::vector<bus> v = {};
// Add two more integers to vector
std::cout<<"enter number"<<std::endl;
std::cin>>temp1;
temp1 = bus1.carNum;
std::cout<<"enter year"<<std::endl;
std::cin>>temp2;
temp2 = bus1.releaseYear;
v.push_back(bus1);
print(v)
}
这里没有令人烦恼的解析。您只需为 bus
类型重载流插入运算符。由于 bus
只有 public 数据成员,这可以是一个非友元函数:
std::ostream& operator<<(std::ostream& stream, bus const& b)
{
stream << "#" << b.carNum << " Year" << b.releaseYear;
return stream;
}
您当然可以根据需要格式化输出。