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;
    }

  • 相关阅读:
    IIS6.0服务器架站无法访问解决方案总结
    DNN中做支持多语言的模块
    在dotnetnuke中创建 parent portal
    DNN,Rainbow资源
    2005年岁末,各种主流CMS系统的比较和汇总
    在DNN中获取所有模块信息
    学习dnn的新资源,sooooooooo great!!
    DNN的电子商务模块
    DNN学习笔记
    也学ASP.NET 2.0 AJAX 之二:使用Timer控件
  • 原文地址:https://www.cnblogs.com/blfbuaa/p/7160571.html
Copyright © 2011-2022 走看看