C++ constexpr 函数定义是不允许的

问题描述 投票:0回答:2

我正在尝试学习 C++,特别是 C++11,因为我们主要学习 C,并且在尝试测试“constexpr”可以做什么时遇到了错误。

测试1:

#include <iostream>;

using namespace std;

int main()
{
    int x = 3;
    int y = 4;
    constexpr int Sum(int a, int b) {return a + b;}
    cout << Sum(x,y);
    return 0;
}

测试2:

#include <iostream>;

using namespace std;

int main()
{
    int x = 3;
    int y = 4;
    constexpr int Sum() {return 3+4;}
    cout << Sum();
    return 0;
}

在这两种情况下,它都给了我以下错误:

E:\C++\Lesson1\main.cpp|9|错误:在“{”标记|之前不允许有函数定义 E:\C++\Lesson1\main.cpp|10|错误:“Sum”未在此范围内声明|

我做错了什么或者我必须对编译器做一些事情吗? (使用代码块并且我启用了 C++11。

c++ constexpr local-functions
2个回答
3
投票

尝试将

constexpr
函数定义移到
main()
之外。


2
投票

你的问题

在预处理器指令后添加分号 (

#include
)。你永远不应该这样做,除非
#define
-ing 某事。这让编译器发疯。此外,除此之外,您不能在函数内定义函数。您必须在外部、全局或类范围内定义它。

解决方案

去掉

#include <iostream>
后面的分号。 将 constexpr 定义移至 above
main()

© www.soinside.com 2019 - 2024. All rights reserved.