如果'Test'是一个普通的类,那么之间有什么区别:
Test* test = new Test;
Run Code Online (Sandbox Code Playgroud)
和
Test* test = new Test();
Run Code Online (Sandbox Code Playgroud) 使用具有自动存储持续时间的内置类型的未初始化对象是未定义的行为.当然,我强烈建议总是在类类型中初始化内置类型的成员变量.尽管如此,我假设如果类类型的相应对象具有静态存储持续时间(即全局对象),则没有初始化器的内置类型的成员总是初始化为零.我的假设是,具有静态存储持续时间的类类型对象的完整内存被清零.
例:
#include <iostream>
using namespace std;
class Foo {
public:
int bar;
};
Foo a;
int main() {
Foo b;
cout << "a.bar " << a.bar << "\n";
cout << "b.bar " << b.bar << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译:
$ g++ -o init init.cpp -Wall -pedantic # gcc 7.2.1
init.cpp: In function ‘int main()’:
init.cpp:14:31: warning: ‘b.Foo::bar’ may be used uninitialized in this function [-Wmaybe-uninitialized]
cout << "b.bar …Run Code Online (Sandbox Code Playgroud) 根据我对声明和定义的理解,在全球范围内:
MyClass instance();//Declares a function that returns a MyClass
MyClass instance;//Declares an instance of MyClass
Run Code Online (Sandbox Code Playgroud)
是否可以声明一个变量并将其定义为在全局范围内使用默认构造函数?如果我使用结构而不是类,该怎么办?
编辑:
好的,MyClass instance;调用默认构造函数也是如此.任何人都可以解释这与这个例子的一致性:
int a; // not default constructed, will have random data
int b = int(); // will be initialised to zero
Run Code Online (Sandbox Code Playgroud) 我创建了一个链表,当我尝试打印节点的值并使用NULL作为绑定时,它不起作用.例如:
#include <iostream>
typedef struct Node;
typedef Node* Node_ptr;
struct Node
{
int i;
Node_ptr next;
};
int main()
{
Node_ptr ptr, head;
ptr = new Node;
head = ptr;
// load
for(int j = 0; j < 4; j++)
{
ptr->next = new Node;
ptr->i = j;
ptr = ptr->next;
}
// print
ptr = head;
while(ptr->next != NULL)
{
std::cout << "print: " << ptr->i << std::endl;
ptr = ptr->next;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此代码时,代码会陷入while循环中的无限循环中.它永远不会理解链表只有5个节点长,它只是继续前进.我不明白为什么会这样.
c++ ×4
constructor ×2
c++-faq ×1
linked-list ×1
new-operator ×1
nodes ×1
pointers ×1
struct ×1