【问题标题】:Access private data member of class from unrelated class in C++ converter constructor从 C++ 转换器构造函数中的不相关类访问类的私有数据成员
【发布时间】:2017-09-13 06:23:09
【问题描述】:

在下面给出的代码中,要访问 B 的私有数据成员,我们可以使用 B 类的成员函数并返回数据成员,然后在构造函数(转换器函数)中将其分配给 A 的数据成员。但我无法这样做。请提出一些帮助。其他方式可以使 Class A 成为 B 的朋友,但需要通过构造函数访问。

#include <iostream>
using namespace std;
class B
{
    int i_;
    public:
        B(int i = 3) : i_(i) {}
        int give() { return i_; }
};
class A
{
   int i_;
   public:
        A(int i = 0) : i_(i) { cout << "A::A(i)\n"; }
        A(const B &b1) : i_(b1.i_) {} // Type casting using constructor
        int display() { cout << i_; }
};
int main()
{
   A a;
   B b; // object is constructed
   a = static_cast<A>(b); // B::operator A(), converting data member of class B to class A
   a.display();
   return 0;
}

【问题讨论】:

    标签: c++ casting


    【解决方案1】:

    遵循@StoryTeller 的建议是不够​​的,您还需要更改 A 的构造函数以使用正确的“getter”方法,以便停止访问私有成员:

    A(const B &amp;b1) : i_(b1.give()) {}

    【讨论】:

      【解决方案2】:

      您的问题是 const 正确性。 int give() 是一个非常量成员函数,只能在非常量对象上调用。但是const B &amp;b1 是对 const 对象的引用。

      由于您在返回整数值时没有修改B 对象,因此通过 const 限定成员函数使您的代码 const 正确:

      int give() const { return i_; }
      

      现在A c'tor 没有尝试非法操作。

      【讨论】:

      • 感谢您提供有用的信息。问题仍然是这样的: prog.cpp: In constructor 'A::A(const B&)': prog.cpp:18:32: error: 'int B::i_' is private in this context A(const B& b1 ) : i_(b1.i_) { } // 使用构造函数进行类型转换 ^~ prog.cpp:6:9: 注意:这里声明为私有 int i_; ^~ 我想知道如何在没有朋友声明的情况下访问 B 的 i_。
      • @KnitahK - 这不是论坛或调试服务。我指出了明显的代码问题。如果您有特定问题,请发帖minimal reproducible example
      • @KnitahK - 该错误表明您没有使用get()。那么问题中的代码与错误有什么关系?
      • 抱歉没有正确提问。我尝试在 A 的转换构造函数中使用 get() 函数,但我想我可能不知道这样做的确切方法。这就是我想问的,编写代码的正确方法。所以请你给我解释一下。
      • @KnitahK - 您可以使用吸气剂。没有不合格的“最佳”方式。它高度依赖于各种因素。 Pick good books 带您了解语言的各个层次。并且写了很多代码。这是只有经验才能教的东西。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      • 2011-05-08
      • 2017-09-10
      • 2011-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多