簡體   English   中英

如何使指針的取消引用包含對對象的引用?

[英]How can I make the dereference of a pointer hold a reference to the object?

當我取消引用指針並將其分配給指針時,它會更改指針指向的內容,而不會為它指向的內容調用operator= 我做了這個程序來證明這一點:

#include <iostream>

struct S
{
    void operator =(int)
    { x = 5; }

    operator int*()
    {
        return &x;
    }

    int x;
};

std::ostream& operator <<(std::ostream& out, S const& s)
{
    return out << s.x;
}

int main()
{
    S s;
    int *x = s;
    *x = 10;

    std::cout << *x;
}

打印出10。 *x = 10不會修改x指向的對象。 我該如何做呢? (歡迎使用C ++ 11解決方案)

您的代碼是未定義的行為。 int *x = S(); x初始化為一個臨時地址,該地址在完整表達式的末尾銷毀,因此*x是非法的。

使用std::reference_wrapper

#include <memory>
#include <functional>

int main()
{
    S s;
    auto x = std::make_shared<S>(std::ref(s));
    *x = 10;

    std::cout << *x; // prints 5
}

這是一個演示。

main函數中的局部x變量的類型pointer to int 它指向的intS實例的S::x 子對象 ,由S::operator int*返回。 取消引用時,您會得到一個類型為int的左值,它仍然是S::x子對象。 因此,當您在此左值int上調用operator=時,它將分派到內置int::operator= ,而不是用戶定義的S::operator=

用戶定義的S::operator=函數不是由類的成員子對象“繼承”的。 我認為這就是讓您感到困惑的地方。

如果你想使用S::operator= ,那么你需要用類型的左值來調用它S

int main()
{
    S s;
    S *x = &s;
    *x = 10;

    std::cout << x->x;
}

將執行您想要的操作,並調用S::operator=

也許您打算定義S類型的x? 當類型為int時,沒有理由調用重載運算符。

暫無
暫無

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

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