c++ - 在 C++ 中创建一个类

标签 c++ class constructor default

在 C++ 中,假设我定义了一个名为 Player 的类,没有默认构造函数。

当我在主函数中创建类实例时:

玩家约翰; 该类将被创建,我可以在调试器中看到它,但 Player Adam() 不会创建该类

为什么在 Player Adam() 中不会创建该类; Adam() 不是会触发没有参数的默认构造函数吗?

没有默认构造函数时使用()和不使用它们有什么区别。

#include<iostream>
class Player{
   
    private:
std::string name{"Jeff"};
double balance{};


    public: 

  
};
int main()
{
     Player John; // the class will be created I can see it in the debugger
     Player Adam();//the class will not be created
    
    
    std::cout<<"Hello world"<<std::endl;
    return 0;
    
    
}

最佳答案

我认为你的问题是你并没有真正创建第二个对象。我把你的代码放在编译器资源管理器here上,您可以在其中看到编译警告:

<source>: In function 'int main()':
<source>:16:17: warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse]
   16 |      Player Adam();//the class will not be created
      |                 ^~
<source>:16:17: note: remove parentheses to default-initialize a variable
   16 |      Player Adam();//the class will not be created
      |                 ^~
      |                 --
<source>:16:17: note: or replace parentheses with braces to value-initialize a variable
Compiler returned: 0

看起来编译器正在将 Player adam(); 解释为函数声明,而不是对象实例化。如果将声明更改为 Player adam{};,或完全删除括号,编译器将“正确”解释此内容,问题应该得到解决。

事实上,在汇编代码中您可以看到对象构造函数 Player::Player 仅被调用一次(您需要将优化更改为 -O0 来看到它,否则它将被内联):

main:
        push    rbp
        mov     rbp, rsp
        push    rbx
        sub     rsp, 56
        lea     rax, [rbp-64]
        mov     rdi, rax
        call    Player::Player() [complete object constructor]
        
        <printing code begins here>

关于c++ - 在 C++ 中创建一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72749220/

相关文章:

c++ - 我在哪里可以找到 C++ csound 教程?

c++ - 无法从映射中恢复指向成员函数的指针

java - 我们可以使用扩展代替实现来使用接口(interface)吗

java:关于重写方法的继承问题

java - 什么时候在 Java 中必须有默认构造函数和参数化构造函数?

c++ - 如何读取二进制文件的全部 64 个字节?

c++ - 统计二进制数中连续1的个数

java - 如何从给定类 Item 获取数组?

java - java反射newinstance构造函数参数数量错误

c++ - 为什么在这个例子中调用了复制构造函数?