【问题标题】:Template function default parameter模板函数默认参数
【发布时间】: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&lt;&lt;pair4(); 仍然会导致 g++ 上的编译错误:ideone.com/9usX9L。此外,还不清楚为什么要在以cout&lt;&lt; 开头的任何一行添加括号——只有当pair4pair1 是一个函数、函数指针或具有operator()() 的类型的对象时,你才能这样做.我很惊讶cout&lt;&lt;pair1();(带括号)完全可以在 MSVC++ 上编译。
  • 您希望pair4() 做什么?该类没有operator()() 成员。你的意思是写cout&lt;&lt;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


【解决方案1】:

除了阴影模板参数(MSVC++ 错误地忽略)等其他错误之外,问题出在:

Pair<int,int> pair4();

这声明了一个函数而不是一个变量。这是因为它在语法上可以是两种,而且 C++ 标准选择了最令人头疼的解析:任何可以被编译器解释为声明的东西,都将被解释为声明。那么链接器错误是您尝试打印到从未定义(没有地址)的函数的cout 地址。

旁注:在 GCC 和 Clang 中,您实际上可以链接它,因为对于 operator &lt;&lt;,地址会立即转换为 bool(没有用于打印指向 ostream 的函数指针的运算符,而 bool 是唯一的可用的隐式转换),这将始终导致true(声明函数的地址永远不能是nullptr),因此地址本身已被优化掉。

修复很简单:

Pair<int,int> pair4;

【讨论】:

  • 我不能投票给你,因为有人在这个问题上对我投了反对票。现在我再次低于 15 岁。顺便说一句,对每个人来说,这个答案都有效。非常感谢。
猜你喜欢
  • 2011-06-11
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-23
  • 2013-02-28
  • 1970-01-01
相关资源
最近更新 更多