【问题标题】:How are private variables accessed in operator overloading? [duplicate]在运算符重载中如何访问私有变量? [复制]
【发布时间】:2016-04-09 19:09:46
【问题描述】:

如何在此代码中的运算符重载(obj.real,obj.imag,res.real,res.imag)中访问私有变量。谁能解释一下

#include<iostream>
using namespace std;

class Complex {
private:
    int real, imag;
public:
    Complex(int r = 0, int i =0)  {real = r;   imag = i;}

    // This is automatically called when '+' is used with
    // between two Complex objects
    Complex operator + (Complex const &obj) {
         Complex res;
         res.real = real + obj.real;
         res.imag = imag + obj.imag;
         return res;
    }
    void print() { cout << real << " + i" << imag << endl; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2; // An example call to "operator+"
    c3.print();
}

【问题讨论】:

  • 这里有什么问题?
  • 类的私有成员只能从同一类的其他成员(或他们的“朋友”)中访问。但是这里 real 和 imag 是私有变量,而 obj 的 real 和 imag 值是从类外部访问的
  • @NiranjanKotha:你在说什么?不,他们不能从课堂外访问。您将运算符定义为类的成员。

标签: c++


【解决方案1】:

C++ 中的访问修饰符(public、private、protected)适用于整个类,而不是单个对象。因此,如果一个类成员是私有的,那么该类的任何成员函数都可以访问它,而不管该成员函数被调用在哪个对象上。

这并不特定于运算符重载。它适用于所有成员函数。

【讨论】:

    【解决方案2】:

    您的运算符 + 应该能够访问所有私有变量,因为它属于同一个类。我认为这里没有问题。但是如果你碰巧在类之外有函数,你可以使用“friend”关键字(通常与流一起使用)。 编译器有错误吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-24
      • 2018-04-28
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-03-02
      • 2011-10-20
      • 2018-10-28
      相关资源
      最近更新 更多