1
#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> >二进制表达式 ( and void)的无效操作数

4

3 回答 3

2

tree.showFamtree()什么都不返回(即void),尝试将它传递给 . 没有任何意义std::cout。你可能会改变

cout<< "Family tree: " << tree.showFamtree() <<endl;

cout << "Family tree: " << endl;
tree.showFamtree();
于 2016-05-25T01:33:34.927 回答
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++ 中称为运算符重载。

于 2016-05-25T01:53:14.323 回答
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;

注意 - 也许标签应该在自己的行上,以便在“树”左侧保持一致的空白。

于 2016-05-25T03:34:41.710 回答