#include <iostream>
using namespace std;
class Fam
{
public:
char you, urmom, urdad;
void addPerson(char y, char m, char f)
{
you = y;
urmom = m;
urdad = f;
}
};
class Tree: public Fam
{
public:
void showFamtree()
{
cout<< "Name: " << you << endl;
cout<< "Mother's name: " << urmom <<endl;
cout<< "Father's name: " << urdad <<endl;
}
};
int main(void)
{
Tree tree;
char a,b,c;
cin >> a;
cin >> b;
cin >> c;
tree.addPerson(a,b,c);
cout<< "Family tree: " << tree.showFamtree() <<endl;
return 0;
}
我想打印家谱 这个人的名字,母亲的名字,父亲的名字 但是当我编译它时,我收到以下错误:
二进制表达式的无效操作数(
basic_ostream<char, std::char_traits<char> >
和void
)
答案 0 :(得分:2)
tree.showFamtree()
不返回任何内容(即void
),尝试将其传递给std::cout
没有任何意义。你可能会改变
cout<< "Family tree: " << tree.showFamtree() <<endl;
到
cout << "Family tree: " << endl;
tree.showFamtree();
答案 1 :(得分:1)
如果你这样定义operator <<
ostream& operator << ( ostream & ostr , const Tree & t ){
ostr << "Name:" << t.you << endl
<< "Mother's name:" << t.urmom << endl
<< "Father's name:" << t.urdad << endl;
return ostr;
}
然后你可以使用
cout<< "Family tree: " << tree <<endl;
这在C ++中称为operator overloading。
答案 2 :(得分:1)
使用类似的东西:
void showFamtree()
{
cout<< "Name: " << you << endl;
cout<< "Mother's name: " << urmom <<endl;
cout<< "Father's name: " << urdad <<endl;
}
使用:
cout << "Family tree: " << tree.showFamtree() << endl;
一种C ++方法是使用std :: stringstream,如:
std::string showFamtree()
{
std::stringstream ss;
ss << "Name: " << you << endl;
ss << "Mother's name: " << urmom <<endl;
ss << "Father's name: " << urdad <<endl;
return (ss.str());
}
我还经常添加标签。所以考虑使用
std::string showFamtree(std::string label)
{
std::stringstream ss;
ss << label;
ss << "Name: " << you << endl;
ss << "Mother's name: " << urmom <<endl;
ss << "Father's name: " << urdad <<endl;
return (ss.str());
}
并将调用更改为
cout << tree.showFamtree("Family tree: ") << endl;
注意 - 也许标签应该在它自己的行上,以便在“树”左侧保持一致的空白区域。