【问题标题】:Can someone explain how the c++ operator= here works?有人可以解释这里的 c++ operator= 是如何工作的吗?
【发布时间】:2019-06-29 17:10:11
【问题描述】:

我有这个小的 c++ 代码 sn-p,有人可以解释一下 operator= 是如何工作的吗?

#include <iostream>
#include <string>

    using namespace std;

    static wstring & test() {
        static wstring test2;
        return test2;
   };


   int main()
   {
       test() = L"Then!";
       wcerr << test() << endl;
   }

【问题讨论】:

  • 我不明白你的实际问题是什么。 = 运算符将一件事分配给另一件事。这有多令人困惑?
  • 这似乎是您关于 references 如何在 C++ 中工作的真实问题;不是赋值。

标签: c++ operator-overloading operators


【解决方案1】:

函数test() 正在返回对静态变量test2 的引用(不是副本)。 static 关键字使函数test 在调用之间保持变量test2 的值。因此,当您调用test() 时,它会返回引用,允许您在test() 中更改test2 的值。这导致wcerr &lt;&lt; test2 &lt;&lt; endl; 打印出“那么!”

请注意,静态关键字根据上下文具有不同的含义。将函数设为静态使该函数仅对文件中的其他函数可见。如果您将静态函数放在标头中,则该标头的每个#include 都会对该函数进行减速。

你可能想说的是

#include <iostream>
#include <string>

using namespace std;

wstring & test() {
   static wstring test2;
   return test2;
}

int main()
{
   test() = L"Then!";
   wcerr << test() << endl;
}

【讨论】:

    【解决方案2】:

    函数test() 返回一个对static 变量test2引用。引用是指一个变量;你可以用变量代替引用。

    这相当于代码:

    static wstring test2;
    int main()
    {
        test2 = L"Then!";
        wcerr << test2 << endl;
    }
    

    在您最喜欢的 C++ 参考资料中搜索“参考资料”。

    【讨论】:

    • 在 VC++ 编译器上,'=' 被定义为 std::wstring::operator=(const wchar_t *_Ptr) 所以被重载。我不明白的是作业是如何工作的,test() = L"Then!";。 test() 是一个函数,怎么可能在函数内部设置静态 wstring?
    • @UnoSolo 你知道 C++ 中的 reference 是什么吗?
    • @UnoSolo 它返回对wstring 的引用,因此在引用所指的对象(即wstring)上执行分配
    • 听到反对票背后的原因会很有趣。
    猜你喜欢
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多