zoukankan      html  css  js  c++  java
  • 类模板与友元函数链接问题

    測试环境:windows 7 vs2013

    1.代码

    #include<iostream>
    
    template<class T>
    class Test
    {
    private:
    	T m_x;
    
    public:
    	friend void print(const Test<T> &test);
    	Test(T x) :m_x(x)
    	{
    	}
    };
    template<class T>
     void print(const Test<T> &test)
    {
    	std::cout << test.m_x<< std::endl;
    };
    int main()
    {
    	Test<int> test(1);
    	print(test);
    
    	std::cin.get();
    	return 0;
    }

    上面的程序编译没有问题,链接时候会报例如以下的错误,错误    2    error LNK1120: 1 个无法解析的外部命令,错误  1  error LNK2019: 无法解析的外部符号 "void __cdecl print(class Test<int> const &)" (?print@@YAXABV?

    $Test@H@@@Z)。该符号在函数 _main 中被引用 。

    解决的方法有两种

    1.将友元函数放入函数内部

    #include<iostream>
    
    template<class T>
    class Test
    {
    private:
    	T m_x;
    
    public:
    	friend void print(const Test<T> &test)
    	{
    		std::cout << test.m_x << std::endl;
    	}
    	Test(T x) :m_x(x)
    	{
    	}
    };
    
    int main()
    {
    	Test<int> test(1);
    	print(test);
    
    	std::cin.get();
    	return 0;
    }

    2.仍旧放在外部,採取声明等方式

    #include<iostream>
    
    template<class T>
    class Test;
    template<class T>
    void print(const Test<T> &test);
    
    template<class T>
    class Test
    {
    private:
    	T m_x;
    
    public:
    	friend void print<T>(const Test<T> &test);//这里<T>不可缺少
    	Test(T x) :m_x(x)
    	{
    	}
    };
    template<class T>
     void print(const Test<T> &test)
    {
    	std::cout << test.m_x<< std::endl;
    };
    int main()
    {
    	Test<int> test(1);
    	print(test);
    
    	std::cin.get();
    	return 0;
    }

  • 相关阅读:
    洛谷[P1002]过河卒
    ACM-Teleportation
    ACM-Team Tic Tac Toe
    Data_Structure04-树
    Data_Structure03-栈和队列
    Data_Structure02-线性表
    Data_Structure01-绪论
    C语言第二次实验报告
    C语言第一次实验报告
    mysql
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7160571.html
Copyright © 2011-2022 走看看