C++成员变量混淆
C++ Member variables confusion
我正在学习C++(来自Java),这简直让我抓狂,说我。。。
class Foo {
public:
Bar &x; // <- This is a ref, Bar is not instantiated (this is just a placeholder)
Bar *y; // <- This is a pointer, Bar is not instantiated (this is just another placeholder)
Bar z; // <- What is this???
};
class Bar {
public:
Bar(int bunchOfCrap, int thatNeedsToBeHere, double toMakeABar);
};
在这个例子中,Bar有一个构造函数,它需要指定一堆字段来创建"Bar"。x和y都没有创建Bar,我知道x创建了一个可以指向Bar的引用,而y创建的指针也可以表示Bar。
我不明白z到底是什么。
这是酒吧吗?如果是这样的话,怎么能给它一个Bar唯一的构造函数呢?
它是属于Foo实例的Bar大小的内存块,可以初始化为Bar吗?
还是别的什么?
谢谢!
出于教学原因,让我们尝试编译以下代码:
class Bar {
public:
Bar(int bunchOfCrap, int thatNeedsToBeHere, double toMakeABar);
};
class Foo {
public:
Bar &x; // <- This is a ref, Bar is not instantiated (this is just a placeholder)
Bar *y; // <- This is a pointer, Bar is not instantiated (this is just a *safer* placeholder)
Bar z; // <- What is this???
};
int main() {
Foo foo;
}
输出:
c++ uuu.cpp -o uuu
uuu.cpp:10:7: error: implicit default constructor for 'Foo' must explicitly initialize the reference member 'x'
class Foo {
^
uuu.cpp:14:10: note: declared here
Bar &x; // <- This is a ref, Bar is not instantiated (this is just a placeholder)
^
uuu.cpp:10:7: error: implicit default constructor for 'Foo' must explicitly initialize the member 'z' which does not
have a default constructor
class Foo {
^
uuu.cpp:16:9: note: member is declared here
Bar z; // <- What is this???
^
uuu.cpp:2:7: note: 'Bar' declared here
class Bar {
^
uuu.cpp:21:9: note: implicit default constructor for 'Foo' first required here
Foo foo;
^
2 errors generated.
make: *** [uuu] Error 1
正如它所说,必须初始化成员引用Bar &x
和成员变量Bar z;
,因为Bar
没有默认构造函数。y
不必初始化,它将默认为NULL
。
x
和y
都间接引用对象。您无法更改x
所指的内容(因此必须在实例化Foo
时对其进行初始化)。您可以更改y
所指的内容。z
是位于Foo
内部的Bar
大小的内存块;要合法地声明这样的成员变量,必须将Bar
的完整定义放在Foo
之前,这样编译器才能知道Bar
有多大
- 是的,它是一个条形:
z
是类型为Bar
的值标识符。如果您没有定义默认构造函数,这将生成编译器错误(编译器通常会这样做,但如果您至少定义了一个已定义的构造->,则不会这样做) - 是的,它是一个条形大小的内存块,在分配
Foo
时分配
这是酒吧吗?如果是这样的话,怎么能给它一个Bar唯一的构造函数呢?
是的,z是一家酒吧。如果Bar
没有默认构造函数,则必须在Foo member initializers list
中初始化Bar
。以下示例忽略x,y初始化:
Foo::Foo(int param1, int param2, int param3)
: z(param1, param2, param3)
{
}
它是属于Foo实例的Bar大小的内存块,可以初始化为Bar吗?
是的,Bar对象在Foo对象内对齐
z
是Bar
的实例,必须在Foo
为时构造,因此:
class Foo {
public:
Foo(…)
: x(<instance of or reference to Bar>),
y(<pointer to Bar>), // optional
z(<Bar ctor params>)
{ … }
请注意,x
和z
都必须在构造期间初始化,而省略y
的初始化是合法的(尽管有问题)。
z
占用与父Foo
实例相同的内存,但它是Bar
的实例,而不仅仅是Bar
大小的内存块。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- C++预处理会生成变量成员、资源库和映射
- 局部堆栈变量成员的返回值优化
- Google Mock:在目标类的构造函数中实例化的模拟私有变量成员
- 使用指向结构变量成员的指针访问该结构的成员的地址
- 如果派生类仅包含自动变量成员,是否有必要具有虚拟驱动器
- 线程安全性和静态变量/成员功能
- "static const char array"可以在 C 语言上包含变量成员吗
- 仅用于内部目的的类的所有变量/成员的技术术语是什么
- 如何强制转换变量成员以将其作为函数的引用参数传递
- 类中未声明变量成员函数
- 在 main 中初始化类的 "static const" 类型变量成员的更好方法
- c++模板类静态const变量成员作为映射键给出未定义引用
- 在类中初始化结构变量成员会导致分割错误
- 在c++中建模变量成员类型
- 模板私有静态变量成员的未定义符号
- 不能访问公共静态变量成员
- 常量变量成员在C++有什么用?
- g++ 4.8.2坚持简单变量成员是数组