麻烦老师出来,指导下,关于我在堆栈里生成对象所出现的你问题。
//C++ CODE
#include <iostream>
using namespace std;
class Vehicle {
public:
Vehicle () {
cout << "Vehicle construct" << endl;
}
virtual ~Vehicle () {
cout << "Vehicle deConstruct" << endl;
}
void Run ();
void Stop ();
protected:
int m_maxSpeed;
int m_weight;
};
class Bicycle : public Vehicle {
public:
Bicycle () {
cout << "Bicycle construct" << endl;
}
virtual ~Bicycle () {
cout << "Bicycle deConstruct" << endl;
}
void setMaxSpeed (int n);
private:
intm_height;
};
void Bicycle::setMaxSpeed (int n) {
m_maxSpeed = n;
}
int main (int argc, char** argv) {
//#define HEAP
//--Way 1: in the stack
#ifndefHEAP
Bicycle bicyc();
//bicyc.setMaxSpeed(100);//这里编译不过
#endif
//--Way 2: in the heap
#ifdefHEAP
Bicycle* bicyc = new Bicycle();
bicyc->setMaxSpeed(100);
delete bicyc;
bicyc = NULL;
#endif
return true;
}
问题1:在way1里,就是在栈里生成对象,然后使用类的方法,但是却编译不过
问题2:在way1里,我将编译不过的地方注释掉,然后再跑,确没有出现我想要在构造和析构出现的文言;如果我在堆里生成对象,都一切正常,这个是为什么,希望老师指点 对象 栈 heap 类 C++
[解决办法]
Bicycle bicyc();
被编译器解释为:
声明一个函数,函数名为bicyc,该函数返回一个Bicycle对象。
改为:
Bicycle bicyc;
使用缺省构造函数初始化不需要加括号。