l

成都手游码农一枚
随笔 - 32, 文章 - 0, 评论 - 117, 引用 - 0
数据加载中……

今天遇到一个有点奇怪的问题,关于模板构造函数。


关于模板Default拷贝构造函数与模板Copy拷贝构造函数(- - 我也不知道该不该这么称呼。。)

#include <iostream>
using namespace std;

template
<typename _Ty>
class Test
{
    
public:
        Test()
{}
        
        Test(
const Test& _t)
        
{
            cout
<<"Default"<<endl;
        }


        template
<typename _Uy>
        Test(
const Test<_Uy>& _t)
        
{
            cout
<<"Copy"<<endl;
        }

}
;

int main()
{
    Test
<int> t;
    Test
<int> d(t);
    Test
<double> f(t);
    
return 0;
}

 
编译错误:

--------------------Configuration: x - Win32 Release--------------------
Compiling...
x.cpp
D:\书籍资料\C++Test\c++作业\asdf\x.cpp(16) : error C2535: '__thiscall Test<_Uy>::Test<_Uy>(const class Test<_Uy> &)' : member function already defined or declared
        D:\书籍资料\C++Test\c++作业\asdf\x.cpp(10) : see declaration of 'Test<_Ty>::Test<_Ty>'
        D:\书籍资料\C++Test\c++作业\asdf\x.cpp(20) : see reference to class template instantiation 'Test<_Ty>' being compiled
D:\书籍资料\C++Test\c++作业\asdf\x.cpp(25) : error C2668: 'Test<int>::Test<int>' : ambiguous call to overloaded function
Error executing cl.exe.
Creating browse info file...

x.exe - 2 error(s), 0 warning(s)



看下面的代码:只是将两个函数位置调换一下就正确了- -;



#include 
<iostream>
using namespace std;

template
<typename _Ty>
class Test
{
    
public:
        Test()
{}
        
        template
<typename _Uy>
        Test(
const Test<_Uy>& _t)
        
{
            cout
<<"Copy"<<endl;
        }


        Test(
const Test& _t)
        
{
            cout
<<"Default"<<endl;
        }


}
;

int main()
{
    Test
<int> t;
    Test
<int> d(t);
    Test
<double> f(t);
    
return 0;
}


正确得到结果:
Default...
Copy...
Press any key to continue



----------------------
VC6.0编译

对于第一种为什么会造成重定义现在还不是很清楚。。

最后决定把这个记录下来。


posted on 2009-10-12 18:49 l1989 阅读(1025) 评论(4)  编辑 收藏 引用 所属分类: C++

评论

# re: 今天遇到一个有点奇怪的问题,关于模板构造函数。  回复  更多评论   

玩模板,就不要用vc6 ……

拷贝构造函数的正确写法是:
Test(const Test<T>& );
2009-10-12 20:50 | OwnWaterloo

# re: 今天遇到一个有点奇怪的问题,关于模板构造函数。  回复  更多评论   

@OwnWaterloo
恩 感谢提醒。
用VS编译一切正常,以后还是用VS测试。

Test(const Test<T>& );
Test(const Test& );
我试过两种写法效果一样,不过我也不知道他们有没有区别。
2009-10-12 22:21 | shly

# re: 今天遇到一个有点奇怪的问题,关于模板构造函数。  回复  更多评论   

@shly
最好还是用Test<T>
2009-10-13 18:21 | 陈梓瀚(vczh)

# re: 今天遇到一个有点奇怪的问题,关于模板构造函数。  回复  更多评论   

@陈梓瀚(vczh)
恩 记住了.
感谢提醒
2009-10-13 18:22 | shly

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理