【问题标题】:access member without getter setter in c++c++ 中没有getter setter的访问成员
【发布时间】:2019-11-01 03:51:49
【问题描述】:

我在使用英语方面很笨拙。希望你能理解。

我们如何在没有 getter 的情况下访问私有成员?看不懂。

当我们了解 C++ 私有、公共、受保护、私有成员或函数时,可以在类范围内访问。

class TestClass {
public:
   TestClass() {
     testMem = 10;
   }

   void testFunction() {
     cout << testMem << endl;
   }
private:
   int testMem;
}

但是,当我看到这段代码时,我真的很困惑。


class B {
public:
    B() {
          testNumber = 10;
        }

        void printMember() {
          cout << testNumber << endl;
        }

private:
    int testNumber;
}

class Money {
public:
    Money();
        bool operator < (Money& amount, B& b) const {
           // this code doesn't make any error
           // why same type member can access their private member directly without getter and setter?
           amount.cents = 10;
           amount.dollors = 10;

           // this Code make a error
           // b.testNumber = 10;

           // below
           // compare code
        } 

private:
    int dollars;
    int cents;
};

我真的很困惑.. 为什么 Money& amount 参数可以在没有 getter 和 setter 的情况下访问他们的私人成员?但是 B 类不能在没有 getter 的情况下访问他们的私有成员。如何..?为什么..?

【问题讨论】:

  • 私有成员被设计成类外的方法不能访问它们。隐私有助于支持松散耦合数据隐藏封装等概念。如果您需要从类之外的方法访问私有成员,我建议您检查您的设计。
  • 此代码仅供测试! umm 相同类型的参数如何在没有 getter 的情况下直接访问其成员?

标签: c++ reference private accessor


【解决方案1】:

第 25 行:b.testNumber = 10;

此代码生成错误,因为 Money 类试图直接访问不同类的私有数据成员。

私有数据成员只能由类本身访问。您可以通过在 B 中创建一个函数来更改数据成员然后调用该函数来更改它来解决此问题。

一个例子:

class B {
public:
    B() {
          testNumber = 10;
        }

        void changeMember(int newData)
        {
            testNumber = newData;
        }

        void printMember() {
          cout << testNumber << endl;
        }

private:
    int testNumber;
}

class Money {
    friend class B;
public:
    Money();
        bool operator < (Money& amount, B& b) const {
           // this code doesn't make any error
           amount.cents = 10;
           amount.dollars = 10;

           // this Code make a error
           b.changeMember(10);

           // below
           // compare code
        } 

private:
    int dollars;
    int cents;
};

【讨论】:

  • 所以我在该行注释了一些评论。 (这段代码出错了。)我真正想知道的是同一个类类型参数如何直接访问它们的私有成员。
  • 我不确定这是否是您的意思,我想您会问为什么这行: bool operator
  • 所以你的意思是 Money 类型参数可以访问他们的私有成员,因为 operator
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多