1.构造函数
主要用于对类的private变量初始化
1 stock::stock(const std::string &co, long n, double pr) 2 { 3 company = co; 4 shares = n; 5 share_val = pr; 6 } 7 8 stock::stock() 9 { 10 shares = 1; 11 company = "no name"; 12 share_val = 1; 13 total_val = 1;
class test1 { public: test1(int a_, int b_ = 1):a(a_),b(b_) { } private: int a; int b; } class test2 : public test1 { test2(int a_, int b_, int a1_, int a2_) : test1(a_, b_), a1(a1_), a2(a2_) {
//这种写法,可以把test1(a_, b_) 的后面去掉
//a1 = a1_;
//a2 = a2_; }
private:
int a1;
int a2;
}
使用:
stock name1= {"name1", 10, 2}; //调用带参数的构造函数 C++11
stock name1("name1", 10, 2);
stock *name1 = new stock( "name1", 10, 2 );
stock name1 = stock( "name1", 10, 2 );
stock name2; //自动调用不带参数的构造函数
2.析构函数
对象过期后,会调用析构函数。什么时候会过期,应该跟作用域有关,没有实际测试。
stock::~stock() { std::cout << "bye, " << company << " "; }
使用:
int main() { { stock name1= {"name1", 10, 2}; stock name2; } while(1); }
运行结果为:bye,name1
bye,no name
注意:上面加了{},如果没有,将不会有显示,因为没有大括号,代码块为整个main();