对象创建引起的 C++ 奇怪的分段错误
通过启动类对象,我遇到了一个奇怪的问题.这个问题很奇怪,也不容易重现.但是,我将尝试举一个说明性的例子.我有继承类.
I have a strange problem by initiating a class object. The problem is as strange as well not easily reproducible. However I will try to give an indicating example. I have inheritance classes.
class BarClass {
public:
BarClass() {
...
}
BarClass(int i, int j) {
...
}
void doSomething() { ... }
};
class FooClass : public BarClass {
public:
FooClass() {
}
FooClass(int i, int j) : BarClass(i,j) {
...
}
};
有时如果我用以下方式启动对象,我会通过初始化得到分段错误错误.
Sometime if I initiate objects with following manner, I will get segmentation fault error by initialization.
FooClass foo1;
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
如果我使用显式指针new,那么没关系..
If I use explicit pointer new, then it is OK..
FooClass *foo1= new FooClass();
foo1->doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
以下代码将在第 2 行给我一个编译器错误.
The following code will give me a compiler error on line 2.
FooClass foo1();
foo1.doSomething();
FooClass foo2(10, 20);
foo2.doSomething();
我应该如何正确地初始化一个对象,尤其是当它有默认构造函数和带有参数的时候.
how should I properly initiate a object, especially when it has default constructor and those with arguments.
推荐答案
你的上一期先...
FooClass foo1();
不会创建 FooClass 类型的对象,而是声明一个名为 foo1() 的函数,该函数不接受任何参数并返回一个 FooClass.删除括号以创建实例,就像您在第一个代码示例中所做的那样.
does not create an object of type FooClass but declares a function called foo1() that takes no parameters and returns a FooClass. Remove the parentheses to create the instance as you did in the first code sample.
为什么你得到一个分段错误可能与你的析构函数有关,我们看不到,这在你的第二个泄漏示例中没有被调用.
why you get a segmmentation fault may have something to do with your destructor which we can't see, and this doesn't get invoked in your second example which leaks.
相关文章