C++ 明显调用的括号前的表达式必须具有(指向)函数类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42604027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:30:05  来源:igfitidea点击:

expression preceding parentheses of apparent call must have (pointer-to-) function type

c++c++11

提问by S.yao

I am learning C++ template on vs2015 community.Here is my code, I want to define a template class and call the member function in the main()function.

我在vs2015社区学习C++模板。这里是我的代码,我想定义一个模板类并调用函数中的成员main()函数。

template <typename T>
class Arithmetic {
    T _a;
    T _b;
    Arithmetic() {};
public
    Arithmetic(T a, T b) :_a(a), _b(b) {};
    T max const() { return _a + _b; };
    T minus const() { return _a - _b; };
};

int main() {
    Arithmetic<int> ar(5,6);
    cout << ar.max() << endl;
}

When I build this program, I get error at the last line. It says:

当我构建这个程序时,我在最后一行出现错误。它说:

Expression preceding parentheses of apparent call must have (pointer-to-) function type

明显调用的括号前面的表达式必须具有(指向)函数类型

What should I do?

我该怎么办?

回答by srinivirt

The error indicates trying to call a function max() that is not defined as a function. Change parenthesis after const keyword to after the identifier max:

该错误表示尝试调用未定义为函数的函数 max()。将 const 关键字后的括号更改为标识符 max 后:

T max const()...

to

T max() const ...

回答by MikeCAT

  • Add required header inclusion and using
  • Add :after public
  • Move constto proper position
  • 添加所需的标头包含和 using
  • 添加:public
  • 移动const到合适的位置
#include <iostream>
using std::cout;
using std::endl;

template <typename T>
class Arithmetic {
    T _a;
    T _b;
    Arithmetic() {};
public:
    Arithmetic(T a, T b) :_a(a), _b(b) {};
    T max() const { return _a + _b; };
    T minus() const { return _a - _b; };
};

int main() {
    Arithmetic<int> ar(5,6);
    cout << ar.max() << endl;
}