【问题标题】:templated conversion constructor fails to access protected data members模板化转换构造函数无法访问受保护的数据成员
【发布时间】:2012-06-12 17:12:44
【问题描述】:

我有一个带有转换构造函数的模板类 Rect,它允许在 Rect 到 Rect 之间进行转换,反之亦然。但是在编译代码时,编译器会给出一个错误,指出构造函数无法访问类的受保护成员。 这是代码:

#include <iostream>
#include <list>
#include <algorithm>

using namespace std;

template< typename T >
class Rect{
protected:
  T width, height;
public:
  Rect(T a, T b){
    width = a;
    height = b;
  }
  template< typename U >
  Rect(Rect<U> const &r){
    width = r.width;
    height = r.height;
  }
  int area(){
    return width*height;
  }
};

int main(){
  Rect<int> a(3,4);
  Rect<float> b(a);
  cout<<b.area()<<endl;
}

这是编译错误:

test.cpp: In constructor ‘Rect<T>::Rect(const Rect<U>&) [with U = int, T = float]’:
test.cpp:28:18:   instantiated from here
test.cpp:10:7: error: ‘int Rect<int>::width’ is protected
test.cpp:18:5: error: within this context
test.cpp:10:14: error: ‘int Rect<int>::height’ is protected
test.cpp:19:5: error: within this context

我想在不使用模板专业化和结交朋友类的情况下解决这个问题。据我所知,您不能将构造函数声明为朋友。有什么想法吗?

编辑:我已对语义进行了更正。所以我正在尝试构建的构造函数实际上是一个转换构造函数。

Edit2:更正了程序。

【问题讨论】:

标签: c++ templates constructor


【解决方案1】:

你应该知道的第一件事是模板构造函数永远不是复制构造函数。第二件事是Rect&lt;T&gt;Rect&lt;U&gt; 其中T != U 是不同的不相关的类,就像std::stringstd::vector 一样不相关。

您应该提供一些访问widthheight 的方法,并且您的转换构造函数应该使用这些访问方法来创建新的Rect

【讨论】:

  • @cdhowie 这会导致编译期间出现部分特化错误。也许如果你能给我们提供一个更好的工作代码。也许我错过了什么。
  • @gibraltar:朋友模板是一个复杂的野兽,你的Rects 不需要提供一种方法来了解他们的 width身高
【解决方案2】:

正如 K-ballo 所提到的,Rect&lt;int&gt;Rect&lt;float&gt; 是不同的类型,并且无法访问彼此的私有成员和受保护成员。您可以通过将以下模板朋友声明添加到您的类 (like so) 来明确允许这样做:

template <typename U> friend class Rect;

在语义上,这意味着“对于任何类型 U,授予类 Rect&lt;U&gt; 访问我的私有和受保护成员的权限”——这是从每个 Rect 实例化到每个其他 Rect 实例化的传出权限授予.

请注意,如果您为 widthheight 添加访问器(正如 K-ballo 建议的那样),则不需要这样做——然后您可以在转换构造函数中使用这些访问器并完全放弃朋友定义。我更喜欢他的解决方案而不是我的解决方案;我给我的只是作为另一种可能的选择,并向您介绍一个您可能不熟悉的概念(朋友,特别是模板朋友)。

【讨论】:

    猜你喜欢
    • 2011-03-22
    • 2013-11-30
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多