c++ - 重载时未在 C++ 中的范围错误中声明

标签 c++ compiler-errors overloading

我在尝试运行这段代码时遇到错误

In function 'int main()':
error: 'area' was not declared in this scope

我找不到问题的明确解决方案。

#include <iostream>

using namespace std;

int main() {

    area(13.3, 67.4);

    return 0;
}

void area(int a, int b){
    cout << "The area is " << a * b << endl;
}

void area(float a, float b){
    cout << "The area is " << a * b << endl;
}

void area(double a, double b){
    cout << "The area is " << a * b << endl;
}

最佳答案

您需要先声明这些函数,然后才能使用它们。

要么前向声明它们:

#include <iostream>

using namespace std;

// forward declarations
void area(int a, int b);
void area(float a, float b);
void area(double a, double b);

int main() {
    area(13.3, 67.4);
    return 0;
}

void area(int a, int b){
    cout << "The area is " << a * b << endl;
}

void area(float a, float b){
    cout << "The area is " << a * b << endl;
}

void area(double a, double b){
    cout << "The area is " << a * b << endl;
}

否则,将实现移至 main() 之上:

#include <iostream>

using namespace std;

void area(int a, int b){
    cout << "The area is " << a * b << endl;
}

void area(float a, float b){
    cout << "The area is " << a * b << endl;
}

void area(double a, double b){
    cout << "The area is " << a * b << endl;
}

int main() {
    area(13.3, 67.4);
    return 0;
}

话虽如此,由于实现完全相同,只是数据类型不同,请考虑改用单个模板函数:

#include <iostream>

using namespace std;

template<typename T>
void area(T a, T b){
    cout << "The area is " << a * b << endl;
}

int main() {
    area<double>(13.3, 67.4);
    return 0;
}

关于c++ - 重载时未在 C++ 中的范围错误中声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52528529/

相关文章:

c++ - 用于将内存块附加到连续内存区域的良好容器

c++ - 是否可以从 unsigned char 数据类型函数向主函数返回一个整数?

java - 如何定义传入 lambda 表达式时将调用哪个重载方法?

c++ - unique_ptr 和 shared_ptr 的重载方法与多态性不明确

c++ - OpenSSL SSL_read 失败(错误 :00000005:lib(0):func(0):DH lib)

c++ - pre-main 全局初始化程序是否保证运行单线程?

c++ - 如何在不创建实例的情况下获取继承结构的基类偏移量

c++ - 命名空间 'std' 中的“atomic_uint32_t”未命名类型错误

c++ - 为什么我在尝试编译时会收到此编译错误?

ios - xcode 没有为我预填充