为什么为包含const数据成员的类不存在默认构造函数 [英] why default constructor is not present for a class containing const data members

查看:163
本文介绍了为什么为包含const数据成员的类不存在默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么默认构造函数不是由包含常量数据成员的类的编译器添加的。
请参见下面的代码,因为我已经声明常量数据成员'a',而试图创建一个类'ClassA'的对象,它说没有合适的默认构造函数是可用的。请帮助。

why default constructor is not added by the compiler for the class containing constant data members. please see the below code , in that i have declared constant data member 'a' and while trying to create object for a class 'ClassA' it is saying No Appropriate Default constructor is available . please help.

#include "stdafx.h"
#include <iostream>
using namespace std;

class ClassA
{
    private:
  const int a;
    public :
  void print()
  {
      cout << "hello world" << endl;
  }
};

int main()
{
  ClassA obj;
  obj.print();
  return 0;
}


推荐答案

在初始化之后,默认构造函数如何为它选择一个值。因此,不会创建默认构造函数

Since a const value cannot change after it is initialized how could a default constructor choose a value for it. So the default constructor is not created

这篇关于为什么为包含const数据成员的类不存在默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆