【发布时间】:2015-02-12 23:44:52
【问题描述】:
//template.h using MSVC++ 2010
#pragma once
#include <iostream>
using std::ostream;
template <typename T, typename U> class Pair {
private:
T first;
U second;
public:
// Pair() ;
Pair ( T x = T() , U y = U() ) ;
template<typename T, typename U>
friend ostream& operator<< ( ostream& thisPair, Pair<T, U>& otherPair );
};
template <typename T, typename U>
Pair<T, U>::Pair ( T x , U y ) : first ( T ( x ) ), second ( U ( y ) )
{cout << x << y;}
template <typename T, typename U>
ostream& operator<< ( ostream& os, Pair<T, U>& otherPair )
{
os << "First: " << otherPair.first
<< " "<< "Second: " << otherPair.second << endl;
return os;
}
//template.cpp
int main()
{
int a = 5, b = 6;
Pair<int,int> pair4();
Pair<int, int> pair1 ( a, b );
cout<<pair4;
cout<<pair1;
return 0;
}
如何让构造函数或成员函数取默认值? 上面的代码在使用 cout 语句时给出了 pair4 的链接器错误。 当 cout
【问题讨论】:
-
注释掉
cout<<pair4();仍然会导致 g++ 上的编译错误:ideone.com/9usX9L。此外,还不清楚为什么要在以cout<<开头的任何一行添加括号——只有当pair4或pair1是一个函数、函数指针或具有operator()()的类型的对象时,你才能这样做.我很惊讶cout<<pair1();(带括号)完全可以在 MSVC++ 上编译。 -
您希望
pair4()做什么?该类没有operator()()成员。你的意思是写cout<<pair4;? -
@j_random_hacker:是的,该代码无法在 GCC 上运行。这就是它在 VS 上的工作方式。 Mooing Duck:如果我实现 Pair(),那么代码将运行良好。我想做 Pair(x=0,y=0)。
-
@Freiza 是的,该代码不适用于 GCC。 I doubt that,GCC 支持
#pragma once。这些不是 VS 特定的错误。 -
有趣的是,当我把它放在 Visual Studio 中时,我得到了error C2065: 'cout' : undeclared identifier。
标签: c++ templates constructor default