首页 > 解决方案 > 使用类方法时的空输出

问题描述

在下面的代码中,直接调用 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");

}

标签: c++templates

解决方案


当然,您不会得到任何输出,因为此方法不会尝试打印任何内容。它只是返回一个数字。

在 main 中执行此操作:

cout << o1.sumit() << endl;
cout << o2.sumit() << endl;

它将直接打印从此方法返回的值。

displayIt或者添加与to相同的逻辑sumit

顺便说一句- 这个问题与 C++ Template 无关。同样的行为也会发生在普通班级中。


推荐阅读