函数调用在C ++中不做任何事情

时间:2018-10-02 10:09:08

标签: c++ return-value

为什么当我调用from PySide2 import QtCore, QtGui, QtWidgets class StandardItemModel(QtGui.QStandardItemModel): checkStateChanged = QtCore.Signal(QtGui.QStandardItem) def setData(self, index, value, role=QtCore.Qt.EditRole): if role == QtCore.Qt.CheckStateRole: last_value = self.data(index, role) val = super(StandardItemModel, self).setData(index, value, role) if role == QtCore.Qt.CheckStateRole and val: current_value = self.data(index, role) if last_value != current_value: it = self.itemFromIndex(index) self.checkStateChanged.emit(it) return val class MainWindow(QtWidgets.QMainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) w = QtWidgets.QTreeView() model = StandardItemModel(w) w.setModel(model) model.checkStateChanged.connect(self.foo_slot) for i in range(4): top_level = QtGui.QStandardItem("{}".format(i)) top_level.setCheckable(True) model.appendRow(top_level) for j in range(5): it = QtGui.QStandardItem("{}-{}".format(i, j)) it.setCheckable(True) top_level.appendRow(it) w.expandAll() self.setCentralWidget(w) @QtCore.Slot(QtGui.QStandardItem) def foo_slot(self, item): print(item.text(), item.checkState()) if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec_()) 函数时它什么都没做?

这是实现阶乘函数的正确方法吗?

factorial

2 个答案:

答案 0 :(得分:9)

factorial的结果将被丢弃,即未绑定到要进一步处理的变量。解决方法很简单:

const int result = factorial(x);

cout << "The result is " << result << "\n";

当C ++ 17 nodiscard属性可以提供帮助时,这是一个很好的演示。如果功能签名显示为

[[nodiscard]] int factorial(int n)

当返回值未绑定到变量时,例如

,编译器会抱怨

factorial(42); // warning: ignoring return value of 'int factorial(int)', declared with attribute nodiscard [-Wunused-result]

答案 1 :(得分:0)

您可以将factorial函数更改为同时通过引用传递,并使用返回值进行递归计算,这样可以避免引用乘法错误:

 int factorial(int &n){
   if (n <= 1){
      return n = 1;
   }
   else {
     int c = n - 1;
     return n = n * factorial(c);
   }

 }

尽管我真的不喜欢这种方法,因为只打印函数的返回值而不是通过传递引用的长度去简单得多。