【发布时间】: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++