簡體   English   中英

此處如何從 class 實例訪問私有數據成員(c++、oops、運算符重載)

[英]How here private data members are accessed from the class instance (c++,oops,operator overloading)

#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 << '\n'; }
};

int main()
{
    Complex c1(10, 5), c2(2, 4);
    Complex c3 = c1 + c2;
    c3.print();
}

這里 operator + 被重載,它正在訪問 res class 的私有成員

更多的例子是 ex1 -

struct Edge {
    int a,b,w;
};
bool operator<(const Edge& x, const Edge& y) { return x.w < y.w; }

ex2-

#include <bits/stdc++.h>
using namespace std;

struct Edge {
    int a,b,w;
    bool operator<(const Edge& y) { return w < y.w; }
};

int main() {
    int M = 4;
    vector<Edge> v;
    for (int i = 0; i < M; ++i) {
        int a,b,w; cin >> a >> b >> w;
        v.push_back({a,b,w});
    }
    sort(begin(v),end(v));
    for (Edge e: v) cout << e.a << " " << e.b << " " << e.w << "\n";
}

ex1 和 ex2 來自 usaco.guide,第一個示例來自 geeks for geeks

誰能解釋它是如何工作的?

此處如何從 class 實例訪問私有數據成員。 誰能解釋它是如何工作的?

首先,在 ex1 和 ex2 中,您使用的是struct ,因此默認情況下每個成員都是public 因此 class 的任何用戶都可以訪問其成員。

現在,即使那些數據成員是private的,您也已將operator+operator<作為成員函數重載。 成員 function 可以完全訪問相應類型 class 的任何( privatepublicprotected )成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM