本文介绍了如果构造函数参数与C ++中的成员变量名称相同,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

部分代码优先:

  class CInner {
public:
CInner(const CInner& another ){// impl here}
private:
//一些成员变量
}

class COuter {
public:
COuter( const CInner& inner):inner(inner){}
private:
CInner inner;

$ / code>

是,在 COuter :: COuter(const CInner& amp ;)该参数与成员变量具有相同的名称。



在VC ++中起作用 - VC ++认为它只是合理的使用参数初始化成员变量,这就是发生了什么 - CInner :: inner 被参数初始化。但是,当使用GCC编译它时,它会以另一种方式进行解释:GCC将自身初始化为 CInner :: inner ,因此它将保持未初始化状态。



哪一种编译器是正确的? 解决方案

真正关于一些特定的编译器来决定什么是合理的,什么不是。语言规范明确指出,在构造函数初始化列表中使用的 inner(inner)中应该查找第一个 inner 在类范围内(即解析为 COuter :: inner ),而第二个 inner 应该在构造函数中查找范围(即解析为构造函数参数内部)。

这就是您所描述的VC ++行为。但是,我发现很难相信GCC在这种情况下会出现错误的行为(除非你有一些古怪的GCC版本)。你确定你没有误解GCC的行为吗?


Some code first:

class CInner {
public:
    CInner( const CInner& another ) { //impl here }
private:
    // some member variables
}

class COuter {
public:
    COuter( const CInner& inner ) : inner( inner ) {}
private:
    CInner inner;
}

Yes, in COuter::COuter( const CInner& ) the parameter has the same name as the member variable.

In VC++ that works - VC++ gets the idea that it is only reasonable to initialize the member variable with the parameter and that's what happens - CInner::inner gets initialized with the parameter. But when the same is compiled with GCC it is interpreted in another way: GCC initializes CInner::inner with itself and so it is left uninitialized.

Which of the compilers is right?

解决方案

It is not really about some specific compiler deciding what's reasonable and what's not. The language specification explicitly says that in inner(inner) used in the constructors initializer list the first inner should be looked up in class scope (i.e. resolve to COuter::inner), while the second innershould be looked up in the constructor scope (i.e. resolve to constructor parameter inner).

This is what you described as VC++ behavior. However, I find it hard to believe that GCC would behave incorrectly in this case (unless you have some weird old version of GCC). Are you sure you haven't misinterpreted GCC's behavior somehow?

这篇关于如果构造函数参数与C ++中的成员变量名称相同,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 12:45