C 如何在没有错误的情况下调用void函数

C++ How to call a void function without errors?

本文关键字:情况下 调用 void 函数 有错误      更新时间:2023-10-16

这是我选择要做的我的分配主要功能(我试图避免)。我认为我缺乏理解在于cout和空隙功能如何共同工作。我试图从功能中删除COUT,但这无法正常工作,我可以进行代码运行的唯一方法是,当我用cout << contact.getInformation() << endl;替换contact.getInformation()时,我试图避免使用CC_2。我只想打电话给 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个改进程序和设计的特定方法。

  1. 除非真正必要,否则不要使用指令。在大多数情况下,针对STD名称空间 - 不是。
  2. 通过参考/参考的非原始类型的通过函数参数,而不是通过值或指针
  3. 了解const关键字和IT用法
  4. 了解构造函数静态初始化bocks
  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;
}

您要问的是不可能的。您设置的两个条件(即1.请勿将空隙函数更改为另一种类型,而2.请勿更改主方法)使得无法以其他方式更改代码预期的结果。

您可以将您的void函数更改为返回"可打印"的东西,例如字符串,您可以将void函数打印到Cout,然后更改主函数以自行调用cout <<构造的上下文。

(或者,最好是在评论中指出的,而不是void,超载<<运算符以使Cout与您的特定对象类型一起工作)

名称 getInformation建议它应该,获取信息,而不是 print it。

因此,您可能想要这个:

  string getInformation() {
    return  "ID: " + to_string(_id) + "n" +
      "NAME: " + _name + "n" +
      "TEL: " + _telephone + "n" +
      "AGE: " + to_string(_age) + "n";
  }

而不是这样:

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

不可能更改maingetInformation