簡體   English   中英

C++ - 好友操作員無法訪問私有數據成員

[英]C++ - friend operator cannot access private data members

我正在嘗試為 class 重載運算符:

#include <iostream>
using namespace std;

class Complex{
    float re, im;
public:
    Complex(float x = 0, float y = 0) : re(x), im(y) { }
    friend Complex operator*(float k, Complex c); 
};

Complex operator*(float k, Complex c) {
    Complex prod;
    prod.re = k * re; // Compile Error: 're' was not declared in this scope
    prod.im = k * im; // Compile Error: 'im' was not declared in this scope
    return prod;
}

int main() {
    Complex c1(1,2);
    c1 = 5 * c1;
    return 0;
}

但是朋友 function 無權訪問私人數據。 當我添加 object 名稱時,錯誤得到解決:

Complex operator*(float k, Complex c) {
    Complex prod;
    prod.re = k * c.re; // Now it is ok
    prod.im = k * c.im; // Now it is ok
    return prod;
}

但是根據我正在閱讀的注釋,第一個代碼應該可以正常工作。 如何在不添加 object 名稱( re而不是c.re )的情況下修復錯誤?

在第一個operator*情況下,編譯器完全不知道reim ,因為 function operator*在這種情況下位於全局空間(范圍)中。

In the second example of operator* you're giving re and im meaning by using an object of a class Complex c - in this case the definition of a class Complex is known to the compiler (is defined above) and it's members re and im也是已知的 - 這就是您在第二個示例中沒有收到錯誤消息的原因。

暫無
暫無

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

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