c++ - C ++如何调用没有错误的void函数?
问题描述
这是我选择做的一项任务,但我不确定如何在cout << contact.getInformation() << endl;
不将 Void 函数更改为其他类型或更改主函数(我试图避免)的情况下修复我收到的错误消息。我认为我对 cout 和 void 函数如何协同工作缺乏了解。我试图从函数中删除 cout ,但这没有用,我可以让代码运行的唯一方法是当我替换cout << contact.getInformation() << endl;
为contact.getInformation()
我试图避免的。我只想在调用时打印 void 函数的内部cout << contact.getInformation() << endl;
欢迎任何帮助!谢谢!
#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 Improvement Your Programs and Designs。
- 除非真的有必要,否则不要使用 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;
}
推荐阅读
- android - 如何找出使用我的应用程序的用户年龄的全部统计数据?
- security - 缓冲区溢出示例
- java - 如何使用 Kafka Publisher 将行数据发布为 Avro 记录
- node.js - 使用 AWS-CDK 部署时无法从 Lambda 服务连接到 Elasticache Redis 集群
- csv - 使用不包括列名的 csv 文件加载 DB2 Warehouse
- time-complexity - 函数仅在循环结束时运行时的时间复杂度?
- vue.js - 当使用带有 Vue 3 组合 API 的自定义 webpack 设置时,输出包非常大
- javascript - 设置状态对象以重新获取时反应查询隐藏错误消息
- ipfs - 如何获取文件夹的 CID?
- java - 字符串到日期格式,反之亦然