这是我选择执行的任务,但是我不确定如何在不将Void函数更改为其他类型或更改main函数的情况下解决我在cout << contact.getInformation() << endl;时遇到的错误消息(我试图避免)。我认为我缺乏理解是cout和void函数如何协同工作。我试图从函数中删除cout,但是那没有用,并且使代码运行的唯一方法是当我尝试将cout << contact.getInformation() << endl;替换为contact.getInformation()时。我只想在调用cout << contact.getInformation() << endl;时打印void函数的内部
欢迎任何帮助!谢谢!

#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

class Contact{

public:
    Contact(int id, string name, string telephone, int age)
    : _id{ id }, _name{ name }, _telephone{ telephone }, _age{ age } {}

    int id() { return _id; }
    string name() { return _name; }
    string telephone() { return _telephone; }
    int age() { return _age; }

    void getInformation() {
        cout << "ID: " + to_string(_id) + "\n" +
        "NAME: " + _name + "\n" +
        "TEL: " + _telephone + "\n" +
        "AGE: " + to_string(_age) + "\n";
    }
private:
    int _id;
    string _name;
    string _telephone;
    int _age;

};

int main() {
    Contact contact{1, "Michael", "555-555-5555", 15};
    cout << contact.getInformation() << endl;
}.


编辑:谢谢大家!我现在看到,这些限制是不可能的。

最佳答案

您提供的代码有很多问题。如果您读了一些不错的C ++书籍,就可以避免使用它们,我的建议是Scott Meyers有效的C ++:55种改善程序和设计的特定方法。


除非确实需要,否则不要使用using指令。在大多数情况下,对于std名称空间-并非如此。
通过引用/常量引用而不是值或指针传递非原始类型的函数参数
了解const关键字及其用法
了解构造函数的静态初始化步骤
了解C ++流


这是您的代码应如下所示:

#include <iostream>
#include <string>

class Contact {

public:
    Contact(int id,const std::string& name,const std::string& telephone, int age):
        _id( id ),
        _name( name ),
        _telephone( telephone ),
        _age( age )
    {}

    int id() const {
        return _id;
    }
    std::string name() const {
        return _name;
    }
    std::string telephone() const {
        return _telephone;
    }
    int age() const {
        return _age;
    }


private:
    int _id;
    std::string _name;
    std::string _telephone;
    int _age;

};

std::ostream& operator<<(std::ostream& to,const Contact& c)
{
    to << "ID: " << c.id() << '\n';
    to << "NAME: " << c.name() << '\n';
    to << "TEL: " << c.telephone() << '\n';
    to << "AGE: " << c.age() << '\n';
    to.flush();
    return to;
}

int main(int argc, const char** argv)
{
    Contact contact = {1, "Michael", "555-555-5555", 15};
    std::cout << contact << std::endl;

    return 0;
}

09-07 06:51