gpt4 book ai didi

c++ - 在编译时找到最大公约数

转载 作者:搜寻专家 更新时间:2023-10-31 01:47:20 25 4
gpt4 key购买 nike

我试图在编译时使用模板找到最大公约数。考虑以下代码:

#include "stdafx.h"
#include <iostream>

template<int N, int M, int K>
class A{
public:
static const int a=A<M,K,M%K>::a;
};
template<int N, int M>
class A<N,M,0>{
public:
static const int a=M;
};

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << A<11,13,11>::a;
return 0;
}

此代码有效,但如果我尝试编写

#include "stdafx.h"
#include <iostream>
template<int N, int M>
class GCD{
public:
static const int a=A<N,M,N%M>::a;
};
template<int N, int M, int K>
class A{
public:
static const int a=A<M,K,M%K>::a;
};
template<int N, int M>
class A<N,M,0>{
public:
static const int a=M;
};

int _tmain(int argc, _TCHAR* argv[])
{
std::cout << GCD<11,13>::a;
return 0;
}

我有崩溃错误 C2059“常量”。

为什么这段代码不起作用?

最佳答案

您需要在顶部对 A 进行前向声明:

template<int N, int M, int K>
class A;

然后它在符合标准的编译器上运行良好。或者您可以将 GCD 移动到所有 A 的下方。

Live example

关于c++ - 在编译时找到最大公约数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19302792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com