c++ - 不带参数调用的函数不会出错

标签 c++ g++

<分区>

当我观察到这一点时,我正在编写一些问题。由于函数应该是一组具有名称的语句,可以从程序的某个位置调用它们。考虑一个给出整数绝对值的简单程序:

#include <iostream>
#include <vector>
using namespace std;

int getAbsolute(int x) {
  return x > 0 ? x : -1*x;
}

int main() {
  vector<int> arr;

  for(int i = -5; i < 5; i++) 
    arr.push_back(i);

  for(int i = 0; i < arr.size(); i++) {
    cout << "abs(" << arr[i] << ") : "
         << getAbsolute << endl;
  }
}

当我运行这个程序时:

rohan@~/Dropbox/cprog/demos : $ g++ testFunction.cpp 
rohan@~/Dropbox/cprog/demos : $ ./a.out
abs(-5) : 1
abs(-4) : 1
abs(-3) : 1
abs(-2) : 1
abs(-1) : 1
abs(0) : 1
abs(1) : 1
abs(2) : 1
abs(3) : 1
abs(4) : 1
rohan@~/Dropbox/cprog/demos : $ 

我的问题是,为什么这个程序没有给我应该用参数调用的错误,我的 g++(-v 4.8.5) 有问题吗?为什么这个程序在每次调用时输出 1?或者我在这里遗漏了什么?我真的很困惑。

最佳答案

这个声明

cout << "abs(" << arr[i] << ") : "
         << getAbsolute << endl;

是正确的。功能指示符getAbsolute隐式转换为函数指针 int (*)( int )根据函数声明

int getAbsolute(int x);

并且使用以下运算符输出此指针 operator <<

basic_ostream<charT,traits>& operator<<(bool n); 

你会得到这样的结果

abs(-5) : 1

因为函数指针不等于零,这个运算符是最好的重载运算符operator <<对于这种类型的函数指针。

关于c++ - 不带参数调用的函数不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41522204/

相关文章:

c++11 - make 没有为 g++ 使用 -std=c++11 选项

c++ - 编译c++文件时出错: Undefined symbols

c++ - MSVC : modifiers not allowed on non-memberfunction

python - 平衡树中的节点数

c++ - 结构 vector push_back C++

c++ - 追加/打印/插入数组 c++ 函数问题

c++ - 从内存映射寄存器读取

c++ - 当我尝试使用ONE LINE编译程序时,g++崩溃

c++ - 有没有办法让 G++/clang++ 的编译时间和 MSVC 一样快?

c++ - 关于异常的编译错误