在C ++中,当没有为类声明构造函数时,如果构造带参数的对象会发生什么?

时间:2017-10-26 02:26:13

标签: c++ oop c++11

我有struct student,我没有声明构造函数。如果我执行以下操作会发生什么?

struct student{
    int assns, mt, finalExam;
    float grade(){…}

}
student billy (60, 70, 80);

1 个答案:

答案 0 :(得分:0)

这个答案是根据问题标题编写的,而不是正文,因为它们似乎严重冲突,希望OP编辑这个。

您将在编译期间遇到错误。

代码:

#include <iostream>
class test
{
   int tt;
};

int main ()
{ 
   test t1 (34);
}

编译错误:

 In function 'int main()': 
  10:17: error: no matching function for call to 'test::test(int)'       10:17: note: candidates are: 
 2:7: note: test::test() 
 2:7: note: candidate expects 0 arguments, 1 provided 
 2:7: note: constexpr test::test(const test&)
 2:7: note: no known conversion for argument 1 from 'int' to 'const test&' 
 2:7: note: constexpr test::test(test&&)  
 2:7: note: no known conversion for argument 1 from 'int' to 'test&&'

这是因为没有定义构造函数接受参数。如果没有ctor,就没有类的意义,因为你永远无法初始化它的数据成员,如果建筑公司本身缺席,你怎么能期望建造一些东西。

编译器将抛出错误。