C++如何无错误地调用void函数?

标签 c++

这是我选择完成的一项任务,但我不确定如何修复我在 cout << contact.getInformation() << endl; 收到的错误消息无需将 Void 函数更改为其他类型或更改 main 函数(我试图避免)。我认为我缺乏理解的是 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 Effective C++: 55 Specific Ways to Improve Your Programs and Designs。

  1. 除非确实需要,否则不要使用 using 指令。在大多数情况下,对于 std 命名空间 - 它不是。
  2. 通过引用/const 引用而不是通过值或指针传递非基本类型的函数参数
  3. 了解 const 关键字及其用法
  4. 了解构造函数静态初始化 block
  5. 了解 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;
}

关于C++如何无错误地调用void函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787092/

相关文章:

c++ - 如何为 Windows 应用程序创建可移动/可调整大小/可配置的工具栏

C++ - 在程序运行时不断更新 WxWidgets 值

c++ - Boost 的链接器错误,在丢弃的部分中引用

C++ Wordsearch 拼图网格二维数组

c++ - 您如何确定全局构造函数的优先级?

c++ - 如果玩家输入无效选择,我如何防止程序继续?

c++ - 无法识别的基于范围的 for 循环?

c++ - 为什么 GDI+ 颜色会根据工具提示是否可见而变化?

c++ - 计算加泰罗尼亚数模质数

c++ - 如何使用 gsoap 初始化服务器上​​下文以启用简单例份验证(仅服务器身份验证)