首页 > 编程 > C++ > 正文

C++ 构造函数 和 函数对象

2019-11-06 06:58:23
字体:
来源:转载
供稿:网友

构造函数在初始化时调用,即使有函数调用运算符()的重载,并且参数类型一样,只会调用构造函数,函数对象只能声明后,才能调用

例子

#include <iostream>#include <string>using namespace std;struct student { string sno; student() { cout << "调用构造函数son为:" << sno << "#"<<endl; } student(string sno) { this->sno = sno; cout << "调用构造函数sno为:" << this->sno << "#" << endl; } void Operator()(string sno) { this->sno = sno; cout << "调用函数对象sno为:" << this->sno << "#" << endl; }};int main(){ student s("2014");//输出"调用构造函数sno为:2014#" student s2; //输出"调用构造函数sno为:#" s("2014"); //输出"调用函数对象sno为:2014#" getchar(); return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选