繁体   English   中英

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

[英]In C++, when no constructor is declared for a class, what will happen if I construct an object with arguments?

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

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

}
student billy (60, 70, 80);

这个答案是根据问题标题而不是正文编写的,因为它们似乎存在严重冲突,希望 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 就没有类的意义,因为你永远无法初始化它的数据成员,如果建筑公司本身不存在,你怎么能期望构造一些东西。

编译器会抛出错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM