c++ - 使用类方法时的空输出
问题描述
在下面的代码中,直接调用 sumit() 函数没有得到任何输出,但是当我通过另一个函数 displayIt() (调用 sumit() )调用它时,它会显示输出。我该如何解决?还请解释发生了什么?
#include<iostream>
#include<string>
using namespace std;
template <typename C>
class ABC
{
private:
C num1, num2;
public:
ABC(C a, C b)
{
num1 = a;
num2 = b;
}
void displayIt()
{
cout << "A+B:" << sumit() << endl;
}
C sumit() { return num1 + num2; }
};
int main()
{
ABC<int> o1(2, 3);
ABC<string> o2("ABC", "XYZ");
//It doesn't display aything...
cout << "Call-1: " << endl;
o1.sumit();
o2.sumit();
//It displays the output...
cout << "Call-2: " << endl;
o1.displayIt();
o2.displayIt();
system("pause");
}
解决方案
当然,您不会得到任何输出,因为此方法不会尝试打印任何内容。它只是返回一个数字。
在 main 中执行此操作:
cout << o1.sumit() << endl;
cout << o2.sumit() << endl;
它将直接打印从此方法返回的值。
displayIt
或者添加与to相同的逻辑sumit
。
顺便说一句- 这个问题与 C++ Template 无关。同样的行为也会发生在普通班级中。
推荐阅读
- python - c: Python API - 在参数变量中重写值
- python - 如何在 selenium 函数中调用方法
- node.js - 节点 - 插入 MongoDB 时抛出异常(字节数组)
- python - 为什么单词边界在 python3 中不起作用?
- python - Python if 语句问题,可能是由于运算符
- php - 在两周内获取第二年的所有日期
- mysql - IF 3 或更多条件 QUERY MySQL
- python - Flask 上的 APScheduler 用于获取数据并保存在停止的位置
- python - 如何在 Python 中找到图形或矩阵的最大连通区域?
- intellij-idea - IntelliJ lombok 插件不兼容