简体   繁体   English

使用重载 = 在 C++ 中进行隐式类型转换

[英]implicit type conversion in C++ using overloaded =

in the below code (which is an example for type conversion):在下面的代码中(这是一个类型转换的例子):

// implicit conversion of classes:
#include <iostream>
using namespace std;

class A {};

class B {
public:
  // conversion from A (constructor):
  B (const A& x) {}
  // conversion from A (assignment):
  B& operator= (const A& x) {return *this;}
  // conversion to A (type-cast operator)
  operator A() {return A();}
};

int main ()
{
  A foo;
  B bar = foo;    // calls constructor
  bar = foo;      // calls assignment
  foo = bar;      // calls type-cast operator
  return 0;
}

in line 21: bar = foo; // calls assignment在第 21 行: bar = foo; // calls assignment bar = foo; // calls assignment it calls the overloaded operator =. bar = foo; // calls assignment它调用重载的运算符 =。 and in the body of class overloading for "=" operator is written in line 12: B& operator= (const A& x) {return *this;} it's statement says "return this".并且在“=”运算符的类重载主体中,第 12 行编写了: B& operator= (const A& x) {return *this;}它的语句是“return this”。 here this points to bar.这里指点一下吧。 and there's just a parameter of type class A: const A& x what does this function do with this parameter?并且只有一个 A 类类型的参数: const A& x这个函数对这个参数有什么作用? and in line 21 what is converted to what by writing: bar = foo;在第 21 行中,通过写入将什么转换为什么: bar = foo; ? ?

The real question you might be asking is what does the operator= function used for?您可能要问的真正问题是 operator= 函数的用途是什么?

Normally we take some data from the constant reference For example通常我们从常量引用中获取一些数据 例如

struct A{
    std::string data;
}

struct B{
    std::string differentData;

    B& operator=(const A& other){
        differentData = other.data;
        return *this;
    }
}

Then if we call code like然后,如果我们调用代码

int main(){
    A a;
    a.data = "hello";
    B b;
    b = a;

    std::cout << b.differentData;
}

We should get "hello" printing to the console我们应该将“hello”打印到控制台

Since you're not interacting with the class given in the function, all this code is doing is running an empty function.由于您没有与函数中给出的类进行交互,因此这些代码所做的只是运行一个空函数。

The return is only used if you chain together equal calls仅当您将相等的调用链接在一起时才使用返回

int main(){
    B b1, b2, b3;

    b3.differentData = "hi";
    b1 = b2 = b3;
    //Pushes hi from b3 >> b2 and returns b2
    //Pushes hi from b2 >> b1 and returns b1
}

what does this function do with this parameter?这个函数用这个参数做什么?

Nothing.没有什么。

what is converted to what by writing: bar = foo;通过写入将什么转换为什么: bar = foo;

Nothing.没有什么。 Or equivalently, the state of bar is replaced from the state of foo .或者等价地, bar的状态被foo的状态替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM