首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >默认和参数化构造函数和对象声明

默认和参数化构造函数和对象声明
EN

Stack Overflow用户
提问于 2022-02-07 04:38:00
回答 1查看 193关注 0票数 2

我写了这段代码:

代码语言:javascript
运行
复制
#include<iostream>

using namespace std;

class Student {
   public:
      string name;
      int age;
      Student() {
         cout<<"Default constructor"<<endl;
      }
      Student(string name, int age) {
         this->name=name;
         this->age=age;
         cout<<"Parameterized constructor"<<endl;
      }
};

int main() {
   system("clear");
   Student s1={"abc", 20};                                                                                                                                                                                                                                                 return 0;                                                                                                                        }

结果:

代码语言:javascript
运行
复制
Parameterized constructor

结论:像这样定义对象s1的调用类的参数化构造函数

检验结论:

代码语言:javascript
运行
复制
#include<iostream>

using namespace std;

class Student {
   public:
      string name;
      int age;
};

int main() {
   system("clear");
   Student s1={"abc", 20};

   return 0;
}

但是,编译上面的代码不会产生任何错误。

问题:

  1. 即使我们没有在类中定义任何参数化构造函数,为什么也没有错误呢?
  2. 当我们将类数据成员定义为私有时,我们会得到一些错误:
代码语言:javascript
运行
复制
5.cpp:12:12: error: no matching constructor for initialization of 'Student'
   Student s1={"abc", 20};
           ^  ~~~~~~~~~~~
5.cpp:5:7: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
class Student {
      ^
5.cpp:5:7: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
5.cpp:5:7: note: candidate constructor (the implicit default constructor) not viable: requires 0 arguments, but 2 were provided
1 error generated.

为什么我们现在要得到这个错误,而不是当数据成员是公开的?:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-07 04:44:15

对于第一种情况,Student有用户声明的构造函数,Student s1={"abc", 20};执行列表初始化,作为效果,选择合适的构造函数Student::Student(string, int)来构造s1

如果上一阶段不产生匹配,则T的所有构造函数都参与对包含大括号元素的参数集的重载解析,.

对于第二种情况,Student没有用户声明的构造函数,它是一个聚合,Student s1={"abc", 20};执行聚合-初始化,因为数据成员nameage直接从"abc"20初始化。

聚合是下列类型之一:

  • ..。
  • ..。类类型(通常是结构或联合),它具有
  • .
    • 没有用户声明或继承的构造函数。

  • ..。

每个direct public base, (since C++17)数组元素,或非静态类成员,按照类定义中数组下标/外观的顺序,从初始化程序列表的对应子句复制初始化。

如果将数据成员设为private,则Student不再聚合。由于不存在适当的构造函数,Student s1={"abc", 20};仍然执行列表初始化并导致错误。

聚合是下列类型之一:

  • ..。
  • ..。类类型(通常是结构类型或联合类型),具有
    • 没有私有或受保护的direct (since C++17)非静态数据成员。

  • ..。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71013555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档