简体   繁体   English

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

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

I have the struct student and I did not declare a constructor.我有 struct student 并且我没有声明构造函数。 What will happen if I do the following?如果我执行以下操作,会发生什么?

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

}
student billy (60, 70, 80);

This answer is written according to the question heading, and not the body, as they seem to be gravely conflicting, hope the OP edits this.这个答案是根据问题标题而不是正文编写的,因为它们似乎存在严重冲突,希望 OP 对此进行编辑。

You will encounter a error during compile time.您将在编译期间遇到错误。

Code:代码:

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

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

Compiler Error:编译器错误:

 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&&'

This happens as there is no constructor defined which takes a parameter.发生这种情况是因为没有定义带参数的构造函数。 Without the ctor there is no meaning of class, as you can never initialize its data member, and how can you expect something to be constructed if the construction company itself is absent.没有 ctor 就没有类的意义,因为你永远无法初始化它的数据成员,如果建筑公司本身不存在,你怎么能期望构造一些东西。

The compiler will throw error.编译器会抛出错误。

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

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