简体   繁体   English

c++ 中没有 getter setter 的访问成员

[英]access member without getter setter in c++

I am clusmy at using English.我在使用英语方面很笨拙。 Hope you can uderstand.希望你能理解。

How can we access private member wihtout getter?我们如何在没有 getter 的情况下访问私有成员? I can't understand it.我无法理解。

When we learned about C++ private, public, protected, private member or function can be accessed at class scope.当我们了解 C++ 私有、公共、受保护、私有成员或 function 时,可以在 class Z31A1FD140BE4BEF2E5D81 访问。

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

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

but, i'm really confused when i saw this code.但是,当我看到这段代码时,我真的很困惑。


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;
};

i'm really confused.. why Money& amount parameter can access their private member without getter and setter?我真的很困惑.. 为什么 Money&amount 参数可以在没有 getter 和 setter 的情况下访问他们的私人成员? But B class can't access their private member without getter.但是 B class 在没有吸气剂的情况下无法访问他们的私人成员。 how..?如何..? why..?为什么..?

Line 25: b.testNumber = 10;第 25 行:b.testNumber = 10;

This code generates an error because the Money class is trying to directly access the private data member of a different class.此代码生成错误,因为 Money class 试图直接访问不同 class 的私有数据成员。

Private data members can only be accessed by the class itself.私有数据成员只能由 class 本身访问。 You could fix this issue by making a function in B to change the data member and then call that function to change it.您可以通过在 B 中创建 function 来更改数据成员,然后调用 function 来更改它来解决此问题。

An example:一个例子:

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;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM