使用默认构造函数初始化变量 [英] Initializing a variable using default constructor
问题描述
我对c ++很新,我现在试图学习所有的基础知识,
我知道当默认构造函数被调用,但是当我尝试不同的语法,它不工作,像我预期的。 / p>
查看下面的代码:
class b();
class c(NULL);
'class'是使用默认构造函数创建的类,
用于a和c工作得很好,但对于b,它只是不会将变量识别为类成员。
因为我看到b和c基本上是一样的,
谢谢!
不要命名类 class $ c $
对于C ++,如果构造函数不带参数,则使用
Foo a; //注意,如果你使用c ++ 11,你可以做Foo a {};
而不是:
Foo b();
这实际上是完全意外的事情,并声明一个名为 b
返回 Foo
实例。
对于 Foo c (null)
,它不会编译,因为没有接受参数的默认构造函数。
*它被称为最烦琐的解析,但我发现这是一个夸张。它可以肯定地抓住你的惊喜,但只是知道你可以声明一个函数原型,应该足以删除烦人的方面。
在其他字 int getMyInt();
显然是放在任何函数定义之外的函数原型。但是,由于也在函数定义内部的情况下, int getMyInt();
不会做任何通常会做的事情...这是定义一个返回整数的函数原型 getMyInt
。
I'm pretty new to c++, i'm now trying to learn all the basics, I know when default constructors are called, but when i tried different syntax it doesn't work like i expected.
Look at the following code:
class a;
class b();
class c(NULL);
'class' is a class i created with default constructor, for a and c everything works well, but for b it just won't recognize the variable as a class member.
As i see it b and c are basically the same, what's wrong than? Thanks!
Don't name your class "class
", as it is a reserved name.
As for C++, if the constructor takes no parameters, you instantiate it using
Foo a; // note, if you are using c++11, you can do Foo a{};
As opposed to:
Foo b();
Which actually does something totally unexpected*, and declares a function named b
that returns a Foo
instance.
As for Foo c(null)
, it won't compile as there is no default constructor that takes an argument.
* It is referred to as "the most vexing parse", though I find that to be an exaggeration. It can certainly catch you by surprise, but just knowing that you can declare a function prototype inside a function, should be enough to remove the "vexing" aspect.
In other words int getMyInt();
is obviously a function prototype when placed outside any function definitions. However, since this is also the case when inside a function definition, int getMyInt();
doesn't do anything it wouldn't normally do... which is to define a function prototype getMyInt
that returns an integer.
这篇关于使用默认构造函数初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!