C ++构造函数初始化列表奇怪 [英] C++ Constructor initialization list strangeness

查看:133
本文介绍了C ++构造函数初始化列表奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写我的类时,我一直是一个好孩子,用所有成员变量前缀m _:

I have always been a good boy when writing my classes, prefixing all member variables with m_:

class Test {
    int m_int1;
    int m_int2;
public:
    Test(int int1, int int2) : m_int1(int1), m_int2(int2) {}
};

int main() {
    Test t(10, 20); // Just an example
}

然而,最近我忘了这样做,写作:

However, recently I forgot to do that and ended up writing:

class Test {
    int int1;
    int int2;
public:
    // Very questionable, but of course I meant to assign ::int1 to this->int1!
    Test(int int1, int int2) : int1(int1), int2(int2) {}
};

相信与否,编译的代码没有错误/警告,只有当我在检查我的代码之前进行最后检查,当我意识到我做了什么。

Believe it or not, the code compiled with no errors/warnings and the assignments took place correctly! It was only when doing the final check before checking in my code when I realised what I had done.

我的问题是:为什么我的代码编译?是C ++标准中允许的类型,还是编译器只是一个聪明的情况?如果你想知道,我在使用Visual Studio 2008

My question is: why did my code compile? Is something like that allowed in the C++ standard, or is it simply a case of the compiler being clever? In case you were wondering, I was using Visual Studio 2008

推荐答案

是的,它是有效的。成员初始化器列表中的名称在构造函数类的上下文中查找,因此 int1 查找成员变量的名称。

Yes, it's valid. The names in the member initializer list are looked up in the context of the constructor's class so int1 finds the name of member variable.

在构造函数本身的上下文中查找初始化器表达式,因此 int1 找到掩蔽成员变量的参数。

The initializer expression is looked up in the context of the constructor itself so int1 finds the parameter which masks the member variables.

这篇关于C ++构造函数初始化列表奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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