【问题标题】:Why am i getting a linker error in my Program saying "Undifined reference"?为什么我的程序中出现“未定义引用”的链接器错误?
【发布时间】:2020-11-22 07:03:24
【问题描述】:

你好…… 我有一个疑问,

cpp 文件

#include <iostream>
#include <vector>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;

int *apply_all(int *array1, size_t size1, int *array2, size_t size2);

void print(const int *const int_ptr, size_t size);

int main()
{
    int array1[]{1, 2, 3, 4, 5};
    int array2[]{10, 20, 30};
    int *int_ptr1{nullptr};
    int *int_ptr2{nullptr};

    int_ptr1 = array1;
    int_ptr2 = array2;

    const size_t ArrSize1{5};
    const size_t ArrSize2{3};
    constexpr size_t size = ArrSize1 * ArrSize2;

    int *int_ptr3 = apply_all(int_ptr1, ArrSize1, int_ptr2, ArrSize2);

    cout << "Array 1 contains : ";
    print(int_ptr1, ArrSize1);

    cout << "Array 2 contains : ";
    print(int_ptr2, ArrSize2);

    cout << "And Array 3 contains : ";
    print(int_ptr3, size);

    cout << endl;

    delete[] int_ptr3;

    return 0;
}

void print(const int *const int_ptr, size_t size)
{
    for (size_t i{0}; i < size; i++)
        cout << *(int_ptr + i) << " ";

    cout << endl;
}

int *apply_all(const int *const array1, size_t size1, const int *const array2, size_t size2)
{
    size_t size = size1 * size2;
    int *int_ptr{nullptr};

    int_ptr = new int[size];

    size_t position{0};

    for (size_t i{0}; i < size2; ++i)
        for (size_t j{0}; j < size1; ++j)
        {
            int_ptr[position] = array1[j] * array2[i];
            ++position;
        }

    return int_ptr;
}

你能告诉我这个解决方案有什么问题吗? 当我构建程序时,它说“对 'apply_all(int*, unsigned int ,int*, unsigned int ) 的未定义引用 collect2.exe:错误 ID 返回 1 个退出状态” 这似乎是一个链接器错误。

【问题讨论】:

  • 在顶部的声明和底部的实现之间,您有 2 个不同的 apply_all() 签名。 const int* 不同于 int*
  • 您可以在声明参数中使用int*,在定义中使用int* const,这样就可以了。但是你不能在声明参数中有int*,在定义参数中不能有const int*。这些不适合。

标签: c++


【解决方案1】:

声明与定义的函数签名不同:

声明:

int *apply_all(int *array1, size_t size1, int *array2, size_t size2);

定义:

int *apply_all(const int *const array1, size_t size1, const int *const array2, size_t size2)

两者必须匹配。由您决定哪一个对您更有帮助。

【讨论】:

    【解决方案2】:

    签名似乎错误。函数定义中的 const int * 和函数声明中的 int*。 apply_all 是函数的名称。

    【讨论】:

    • 我明白了。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2012-12-10
    • 1970-01-01
    • 2014-06-01
    • 2019-11-25
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多