简体   繁体   English

C ++成员初始化VS继承的构造方法初始化

[英]C++ member initialization VS inherited constructor initialization

I know that one way to initiate members of a class is to write the following: 我知道初始化类成员的一种方法是编写以下代码:

class base {
 int id;
 public:
 base(int id): id(id){}
};

But what if I mix this syntax with constructor initialization of a derived class : 但是,如果我将此语法与constructor initialization of a derived class混合在一起怎么办:

class base {
 int id;
 public:
 base(int id): id(id){}
};

class dri : public base {
 int base;
 public:
 dri(int id): base(id){}
};

In the example above under the derived class, is base(id){} referring to int base or class base ? 在上面的示例中,在derived类下, base(id){}是指int base还是class base I assume it is referring to int base since is' not compiling. 我认为它是指int base因为它没有编译。 How can I make it refer to class base ? 我怎样才能使它参考class base

Edit: 编辑:

Second question, let's say you look at a random C++ code which looks like this: 第二个问题,假设您看一个看起来像这样的随机C ++代码:

class base {
 int id;
 public:
 base(int id): id(id){}
};

How can you tell if id(id){} is initializing a local variable or initializing another classes constructor? 您如何判断id(id){}是正在初始化局部变量还是正在初始化另一个类的构造函数?

Don't reuse the identifier base is the simplest advice. 最简单的建议是不要重用标识符base

More complex would be use scope resolution: 更复杂的是使用范围解析:

dri(int id): ::base(id){}
              ^
              use base from the global namespace

Post question edit answer: 发表问题编辑答案:

The most recently defined use of an identifier will be used over definitions in outer scopes unless an outer scope is explicitly specified. 除非明确指定外部作用域,否则将在外部作用域的定义上使用最近定义的标识符用法。 There is no good way to tell which you will get without acting like the compiler and building a graph of what identifiers are defined and where and performing the resolution yourself. 如果没有像编译器那样的作用,并且没有建立自己定义定义的标识符的图形以及在何处执行解析的图表,没有什么好方法可以告诉您。

What you've run up against is exactly the same as 您遇到的挑战与

int string; 
string test; 

by the time the compiler reaches string test , the meaning of string has been changed by the programmer from a type to a variable of type int . 由编译器到达时间string test ,的含义string已经改变由程序员从一个类型到类型的变量int There is no solution for this other than don't do it. 除了不做之外,没有其他解决方案。

This brings us back to the opening point: Don't reuse identifiers in encompassed scopes without good reason. 这使我们回到了起点:不要在没有充分理由的情况下在包含的范围内重用标识符。 Someone will screw it up. 有人会把它搞砸的。

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

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