初始化程序列表和赋值重载(运算符=) [英] Initializer lists and assignment overloading (operator =)

查看:103
本文介绍了初始化程序列表和赋值重载(运算符=)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

赋值运算符的重载是否传播到初始化列表?

Does the overloading of the assignment operator propagate to an initializer list?

例如,假设一个类:

class MyClass {
    private:
        std::string m_myString; //std::string overloads operator =
    public:
        MyClass(std::string myString);
}

还有一个构造函数:

MyClass::MyClass(std::string myString)
 : m_myString(myString)
{
}

初始化器列表会解决std::string上的赋值运算符重载吗?如果没有,是否有解决方法?

Will the initializer list work out the assignment operator overload on std::string? And if not, is there a workaround?

特别是对于GCC.

推荐答案

我认为您缺少的是assignmentinitialization之间的区别.

I think what you are missing is the difference between assignment and initialization.

让我们看一个具有基本类型的简单示例:

Lets look at a simple example with a fundamental type:

int a = 10; // Initialization
a = 1; // Assignment

上面的例子很简单,并不难理解.但是,当您进入用户定义的类型时,它并不是那么简单,因为对象是构造的.

The above example is simple and not difficult to understand. However, when you get into user-defined types, it is not as simple because objects are constructed.

例如,让我们看一下std::string

std::string s1("String1"); // Initialization (constructs s1 using constructor)
std::string s2 = s1; // Initialization (constructs s2 using copy constructor)
std::string s3(s2); // Initialization (constructs s3 using copy constructor)

s1 = s2; // Assigns s2 to s1 using assignment operator

这里的关键是operator=表示在不同上下文中的不同事物.这完全取决于左侧上的内容.

The key thing here is operator= means different things in different contexts. It all depends on what is on the left hand side.

  std::string s1 = "Hello"; // Lhs has std::string s1, so this is initialization
  s1 = "Bob"; // Lhs has only s1, so this is assignment

初始化器列表仅进行初始化(因此名为 initializer 列表).

And initializer lists do initialization only (hence the name initializer list).

MyClass::MyClass(std::string myString)
 : m_myString(myString) // Initialization
{
}

请注意,当您在构造函数的主体中调用operator=时,您现在正在执行赋值操作而不是初始化.

Just be aware, when you call operator= in the body of the constructor, you are now doing assignment and not initialization.

MyClass::MyClass(std::string myString)
{
    // m_myString(myString); <-- Error: trying to call like a function
    m_myString = myString; // Okay, but this is assignment not initialization
}

这篇关于初始化程序列表和赋值重载(运算符=)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆