【问题标题】:Accessing private member variables inside public member function在公共成员函数中访问私有成员变量
【发布时间】:2015-11-25 19:59:56
【问题描述】:

在函数myfun 中有没有一种方法可以访问rhs.var 而无需编写返回var 的公共函数?另外,据我了解,这是因为 rhs 可能是不同的类型......这是正确的吗?

#include <iostream>

template<class T>
class foo
{
private:
    T var;

public:
    foo(T v) : var(v) {}

    template<class Type>
    void myfun(foo<Type>& rhs)
    {
        auto i = rhs.var; //BOOM
    }
};

int main()
{
    foo<int> a = 5;
    foo<double> b = 2.2;

    a.myfun(b);
}

【问题讨论】:

  • 你可以在foo中使用template &lt;typename U&gt; friend class foo;
  • @Dieter Lücking 如此简单......从来没有想过

标签: c++ class templates


【解决方案1】:

建议的解决方案

您可以为您的私有成员变量提供公共访问器:

template<class T>
class foo {
  T var;
public:
  foo(T v) : var(v) {}
  T getVar() const { return var; }
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  template<class Type>
  void myfun(foo<Type>& rhs) {
    auto i = rhs.getVar();
                 ^^^^^^^^
  }
};

或者正如 Dieter 在 cmets 中已经提到的,您可以让您的模板类成为朋友:

template<class T>
class foo {
  T var;
  template <class> friend class foo;
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
public:
  foo(T v) : var(v) {}
  template<class Type>
  void myfun(foo<Type>& rhs) {
    auto i = rhs.var;
  }
};

概述

模板成员函数myfun没有被授予访问类模板foo的私有成员变量var的原因是编译器将class foo&lt;Type&gt;class foo&lt;T&gt;解释为完全不同的类类型,即使它们会源自相同的模板类定义。因此,作为不同的类类型,一个不能访问另一个的私有成员。

【讨论】:

  • 你甚至可以删除U, template &lt;typename&gt; friend class foo;
【解决方案2】:

您可以将第二种类型定义为油炸:

template<class T>
class foo
{
private:
    T var;

public:
    foo(T v) : var(v) {}

    template<class Type>
    void myfun(foo<Type>& rhs)
    {
        auto i = rhs.var; //BOOM
    }

    template<class Type> 
      friend class foo;
};

live example

【讨论】:

    猜你喜欢
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2016-05-20
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    相关资源
    最近更新 更多