gpt4 book ai didi

C++ undefined reference 构造函数错误?

转载 作者:行者123 更新时间:2023-11-28 05:57:05 25 4
gpt4 key购买 nike

我是 C++ 的新手,在解决我遇到的 undefined reference 问题时遇到困难。我正在尝试创建一个测试类,它将一个数组作为构造函数的输入,如果我将所有内容都放在一个文件中,一切似乎都能正常工作,如下所示:

main.cpp

#include <iostream>

class Test
{
public:
template<typename T,int SIZE>
Test(T (&array)[SIZE]);
};

template<typename T,int SIZE>
Test::Test(T (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}

int main()
{
int myIntArray[10];
Test myTest(myIntArray);
return 0;
}

当我运行这个例子时,我得到以下输出:

Array constructor was called
Size of array is: 10

但是,当我将这个示例分解为以下三个文件时:

测试.h

class Test
{
public:
template<typename T,int SIZE>
Test(T (&array)[SIZE]);
};

测试.cpp

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

template<typename T,int SIZE>
Test::Test(T (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}

主要.cpp

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

int main()
{
int myIntArray[10];
Test myTest(myIntArray);
return 0;
}

我收到 an undefined reference to Test::Test<int, 10>(int (&) [10])' .我不确定我做错了什么,我想也许我忽略了一些东西。任何见解将不胜感激。感谢您的帮助。

最佳答案

问题是您将模板函数声明和模板函数定义分开。当你定义一个模板函数时,你的函数声明和它的定义必须放在一起。如果不位于同一位置,则应在 .tpp 文件中定义模板函数,然后将该 .tpp 文件包含在声明模板函数的头文件中。

为什么需要这样做?与预先知道参数类型的普通函数不同,编译器会为每次调用不同类型的函数加载一个版本的模板函数。所以,在你的情况下,当你这样做时,

int main() 
{
int myIntArray[10];
Test myTest(myIntArray);
return 0;
}

编译器所做的是,定义一个函数定义,

Test::Test(int (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}

并将其加载到内存中。但是,如果编译器必须执行此操作,则当它试图查看头文件中的声明时,它必须能够访问函数的定义。当您将函数的定义放在单独的 .cpp 文件中时,编译器无法访问函数的定义,因此无法根据用户输入定义函数并将其加载到内存中。

就像我提到的,如果你想将实现与定义分开,你可以将模板函数的定义放在一个 .tpp(这是一个专门用于模板函数定义的文件)文件中,并将其包含在你的 .tpp 文件中。 H。像这样。

测试.h :

class Test
{
public:
template<typename T,int SIZE>
Test(T (&array)[SIZE]);
};

#include "Test.tpp"

测试.tpp

#include <iostream>

template<typename T,int SIZE>
Test::Test(T (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}

主要.cpp

#include <iostream>

template<typename T,int SIZE>
Test::Test(T (&array)[SIZE])
{
std::cout << "Array constructor was called" << std::endl;
std::cout << "Size of array is: " << SIZE << std::endl;
}

希望这对您有所帮助。

关于C++ undefined reference 构造函数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949869/

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