【问题标题】:Getting method is undefined in C++获取方法在 C++ 中未定义
【发布时间】:2017-09-06 03:20:58
【问题描述】:

我正在尝试根据 C++ 教程创建程序。但是导师用的IDE是VS2010,我用的是VS2017。我注意到一些语法(sp.)略有不同。我不确定这个错误是什么,我已经尝试过搜索。

这是主要的 .cpp:

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

    using namespace std;

    int main()
    {
        int x;
        cout << "Enter a Number: " << endl;
        cin >> x;

        if (IsPrime(x))
            cout << x << " is prime" << endl;
        else
            cout << x << " is not prime" << endl;

        if (Is2MorePrime(x))
            cout << x << "+2 is prime" << endl;
        else
            cout << x << "+2 is not prime" << endl;


        return 0;
    }

在 if 条件中测试的方法都返回“包含的方法:未找到标识符”和“包含的方法:标识符未定义”

这是包含的类 .cpp:

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

    using namespace std;


    bool Utility::IsPrime(int num)
    {
    bool prime = true;
        for (int i = 0; i <= num / i; i++)
        {
            int factor = num / i;
            if (factor*i == num)
            {
                cout << "Factor Found: " << factor << endl;
                prime = false;
                break;
            }
        }

        return prime;
    }

    bool Utility::Is2MorePrime(int num)
    {
        num += 2;
        return IsPrime(num);
    }

这是包含的头文件:

    #pragma once

    class Utility
    {
        bool IsPrime(int primeNum);

        bool Is2MorePrime(int morePrime);
    };

我还是 C++ 编程的新手,所以我还不知道任何密集的东西。

【问题讨论】:

  • 您收到错误,因为main 调用IsPrime,但没有这样的功能——只有Utility::IsPrime。您正在创建一个不需要的类UtilityIsPrimeIs2MorePrime 应该只是在头文件中定义并在 .cpp 中实现的函数。
  • 你正在使用一个类作为命名空间。

标签: c++ undefined-function


【解决方案1】:

这些方法在 Utility 类中,但您从 main 调用它们,没有 Utility 的实例,因此编译器/链接器正在寻找不存在的方法。

您可以将它们设为Utility 的静态成员,然后您只需要限定调用范围(例如Utility::IsPrime(x)),而实际上并没有Utility 的实例。

正如 @Amadeus 在 cmets 中提到的:如果 Utility 中的所有内容都是“无状态的”并且可以是静态的,那么也许您应该将所有 Utility 方法放在命名空间而不是类中。

【讨论】:

  • 非常感谢@John3136。我在头文件中将方法设置为静态(例如static bool IsPrime(int x)),并像您所说的那样限定了调用范围(例如if (Utility::IsPrime(x)))并且它起作用了。
猜你喜欢
  • 1970-01-01
  • 2011-04-07
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-02
  • 2011-06-19
相关资源
最近更新 更多