欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 【C++】构造函数

【C++】构造函数

2025/4/20 5:15:39 来源:https://blog.csdn.net/qq_45951891/article/details/143824836  浏览:    关键词:【C++】构造函数

引入:

有这样一个学生类

class Student {
public:int classN;int age;bool sex;const char* name;void introduceMyself() {std::cout << "Hello,everyone!My name is " << name << std::endl;}
};

我们创建一个对象,并调用introduceMyself()方法,会报错

int main() {Student stu;stu.introduceMyself();
}

因为name没有被初始化,需要被赋值

在Java中数据基本类型如int和float会自动初始化为0

但在C++中你必须手动初始化所有基本类型

那我们定义一个初始化名字的方法。并在创建对象后首先调用它

#include<iostream>
class Student {
public:int classN;int age;bool sex;const char* name;void Init() {name = "未命名";}void introduceMyself() {std::cout << "Hello,everyone!My name is " << name << std::endl;}
};
int main() {Student stu;stu.Init();stu.introduceMyself();
}

这样写很麻烦,当我们构造对象时,如果有办法直接运行这个初始化代码就好了

构造函数来拯救你啦

#include<iostream>
class Student {
public:int classN;int age;bool sex;const char* name;Student() {//这就是构造函数name = "未命名";}void introduceMyself() {std::cout << "Hello,everyone!My name is " << name << std::endl;}
};
int main() {Student stu;stu.introduceMyself();
}

构造函数用来在创建对象时初始化对象,即为对象的成员变量赋初始值

  • 构造函数名和类名相同
  • 构造函数没有返回值类型和返回值
  • 构造函数可以重载,需要满足函数重载的条件

构造函数的调用时机:

  1. 栈区对象的产生
  2. 堆区对象的产生

构造函数在类实例化对象时会自动调用

既然可以重载,那就说明还有带参的构造函数

示例:

#include<iostream>
class Student {
public:Student(){}//无参构造Student(int a){}//有参构造
};
int main() {Student stu1;//定义一个类对象,默认调用无参构造Student stu2 = { 18 };//隐式调用有参构造Student stu3(20);//显式调用有参构造Student* StuP = new Student;//堆区对象也会自动调用构造函数
}
  • 如果一个类中没有显式地给出构造函数,系统会自动地给出一个缺省的(隐式)构造函数
  • 如果用户提供了无参(有参)构造,那么系统就不再提供默认构造
  • 如果类中只有有参构造,没有无参构造,那么就不能调用默认构造的方式初始化对象,想用这种方式初始化对象,就要提供无参构造

假设你有一个Log类,它只有静态的write()方法

class Log{
public:static void write(){}
};

你只想以这种方式使用Log类:Log::write();

不希望可以创建实例:Log l;

有两种解决方法

1.设置为private来隐藏构造函数

class Log{
private:Log(){}
public:static void write(){}
};
class Log{
public:Log() = delete;static void write(){}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词