本文核心
C++目前我知道的有三种方式可以生成一个类,以前总是搞混,今天有空了总结一下。
析构函数的声明和定义
-
构造函数的参数表示的不是类成员,而是要赋给类成员的值,因此参数名不能与类成员相同
-
构造函数是类在初始化的时候会被自动调用的函数
下面放上一个构造函数的例子
#include <iostream> #include <string> using namespace std; /******************************************/ /*类的声明*/ class stock { public: //构造函数声明 //构造函数前面没有**void int**等值,且其需要放在**Public**里面 stock(const string company_, long shares_, double shares_val_); void OutPut(); private: string company; long shares; double shares_val; }; /*打印刚刚输入的值*/ void stock::OutPut() { cout << company << endl; cout << shares << endl; cout << shares_val << endl; } /*写构造函数内容,这里要注意 1.campany_是构造函数的形参 2.campany是类的成员,两者不一样,可以在构造函数中把形参赋给类的元素,但不能把类的成员放在函数的形参 的位置,直接让它们读取数据 */ stock::stock(const string company_, long shares_, double shares_val_) { company = company_; shares = shares_; shares_val = shares_val_; } /***************************************************/ int main() { using namespace std; //const string ab = "wang"; stock food("wang",1,2.0); food.OutPut(); stock food2 = stock("wang2", 1, 2.0); food2.OutPut(); stock* food3 = new stock("wang3",1,2); food3->OutPut(); }
上述函数运行的结果为
如何生成一个新的类以及 构造函数的使用
显式调用
stock food2 = stock("wang2", 1, 2.0);
food.OutPut();
隐式调用
stock food("wang",1,2.0);
food2.OutPut();
使用new初始化
stock* food3 = new stock("wang3",1,2);
food3->OutPut();
构造函数调用的总结
我们使用了三种方式调用了构造函数,其中显示调用和隐式调用后,再调用类的函数都使用food2.OutPut();
而使用new初始化后的,再调用类的函数都使用food3->OutPut();