English 中文(简体)
如果C++中的构造函数参数与成员变量同名,会发生什么?
原标题:What if a constructor parameter has the same name as a member variable in C++?

一些代码:

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;
}

是的,在<代码>COuter:COuter ( const CInner& >中,该参数的名称与成员变量相同。

在VC++中运行正常 - VC++理解用参数初始化成员变量才是合理的,于是就发生了这种情况 - CInner :: inner 由参数初始化。但是当使用GCC编译时,它以另一种方式解释:GCC用CInner :: inner 初始化它本身,所以它没有初始化。

哪个编译器是正确的?

问题回答

实际上,这并不是某个特定编译器决定什么是合理的,什么是不合理的。语言规范明确指出,在构造函数初始化列表中使用inner(inner)时,应该在类作用域中查找第一个inner(即解析为COuter::inner),而第二个inner应该在构造函数作用域中查找(即解析为构造函数参数inner)。

这就是你描述的VC++行为。然而,我难以相信GCC在这种情况下会表现不正确(除非你有一些奇怪的旧版本的GCC)。你确定你没有误解GCC的行为吗?

Visual C++ 是正确的。我怀疑您在测试中使用的是较旧版本的 gcc ,至少我记得,较新的版本可以正确处理此问题。这在标准的§12.6.2/7中有所涵盖,其中给出了以下示例:

class X {

    int a;
    int b;
    int i;
    int j;

public:
    const int& r;

    X(int i): r(a), b(i), i(i), j(this->i) {}

};

initializes X::r to refer to X::a, initializes X::b with the value of the constructor parameter i, initializes X::i with the value of the constructor parameter i, [ ...]





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签