&, Vec2 const-6ren">
gpt4 book ai didi

c++ - C++ 中的通用 ostream 问题

转载 作者:行者123 更新时间:2023-11-30 03:34:53 25 4
gpt4 key购买 nike

我尝试做一个通用 vector ,但是当我编译它时抛出这个错误:

Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Vec2<int> const&)", referenced from:
referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

请有人帮助我。这是代码:

#include <iostream>

template<typename T>
class Vec2 {
public:
Vec2(T x, T y):x(x), y(y) {}
friend std::ostream &operator <<(std::ostream &, const Vec2<T> &);
private:
T x;
T y;
};

template<typename T>
std::ostream &operator << (std::ostream &os, const Vec2<T> &vec) {

os << "x: " << vec.x << ", y: " << vec.y << std::endl;

return os;
}


int main(int argc, const char * argv[]) {

Vec2<int> vi(3, 4);

//Vec2<float> vf(3, 4);

std::cout << vi;

//std::cout << vf;

return 0;
}

当我不使用模板时,代码可以工作。

最佳答案

我收到警告:

main.cpp:7:66: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const Vec2<T>&)' declares a non-template function [-Wnon-template-friend]
friend std::ostream &operator <<(std::ostream &, const Vec2 &);
^
main.cpp:7:66: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)

您正在声明一个非模板 operator<<作为 friend 。你应该声明你定义为友元的函数模板:

template<typename U>
friend std::ostream &operator <<(std::ostream &, const Vec2<U> &);

关于c++ - C++ 中的通用 ostream 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41686397/

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