[在C ++中没有getter setter的访问成员

问题描述 投票:0回答:1

我不太会英语。希望你能理解。

我们如何才能获得私人会员?我听不懂。

当我们了解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的情况下访问其私有成员。怎么样..?为什么..?

c++ reference private accessor
1个回答
0
投票

第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;
};
© www.soinside.com 2019 - 2024. All rights reserved.