【发布时间】:2021-09-19 23:42:29
【问题描述】:
我正在使用 Microsoft Visual Studio 作为源代码编辑器,当我尝试编译以下代码时出现链接器错误:
LNK2019 未解析的外部符号 "class std::basic_ostream
> & __cdecl operator > &,类 X &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$X@H@@@Z) 在函数 _main Zadatak7 中引用.19.04.2021 C:\Users\AT95\Desktop\Zadatak7.19.04.2021\Zadatak7.19.04.2021\main.obj 1
我必须怎样做才能使这个程序正常工作?
我想让你看一下重载operator<<的定义,因为
该方法导致错误。
#include <iostream>
template <class T>
class X
{
private:
int index, capacity;
T* collection{};
public:
X(const int nmb, const T* array)
{
index = 0;
capacity = nmb;
collection = new(T[nmb]);
for (int i = 0; i < nmb; i++)
collection[index++] = array[i];
}
X(const X& other)
{
index = other.index;
capacity = other.capacity;
collection = new(T[other.capacity]);
if(other.index < other.capacity)
for (int i = 0; i < other.index; i++)
collection[i] = other.collection[i];
}
~X() { delete[] collection; }
friend std::ostream& operator<<(std::ostream&, X<T>&);
};
template <class T>
std::ostream& operator<<(std::ostream& out, X<T>& other)
{
for (int i = 0; i < other.index; i++)
out << i + 1 << ". " << other.collection[i];
return out;
}
int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, n = sizeof(array)/sizeof(int);
X<int> x(n, array), b(x);
std::cout << x;
return 0;
}
【问题讨论】:
-
收集一系列警告 - 实时 - godbolt.org/z/3n841MbMj - 以我的方式解决它们。
-
非常有用的网站,我会尽我所能去看看。朋友,谢谢。非常感谢您的帮助。
-
@AndrejTrozic 无论是否使用该站点,提示都是打开编译器警告并阅读它们。他们会告诉你你的代码在哪里看起来有问题。
-
该站点也很有帮助,因为很高兴了解其他编译器对您的代码的看法。不同的编译器给出不同的诊断,一个编译器可能会发现其他人没有发现的问题或更好地解释问题。它们会生成不同的输出并对some coding mistakes 有不同的解释,并且它们输出中的差异有助于发现隐秘的错误。