首页 > 解决方案 > 使用大括号和圆括号

问题描述

所以我正在做一个初学者C++课程,我对括号和花括号的一些事情感到困惑..

#include "Savings_Account.h"

Savings_Account::Savings_Account(double balance, double int_rate)
    : Account(balance), int_rate{int_rate} {
        
    }

Savings_Account::Savings_Account() 
    : Savings_Account{0.0, 0.0} {
        
    }

注意:Savings_account 是从 Account 类派生的类

在导师编写:Account(balance)的第二行代码中,他说他正在委托帐户类的重载构造函数,这有点道理但是......还有更多

class Derived : public Base {
private:
    int doubled_value;
public:
    Derived() : 
        Base {}  {
            cout << "Derived no-args constructor " << endl; 
    }
    Derived(int x) 
        : Base{x} , doubled_value {x * 2} { 
            cout << "int Derived constructor" << endl; 
    }
    Derived(const Derived &other)
        : Base(other), doubled_value {other.doubled_value} {
         cout << "Derived copy constructor" << endl;     
    }

在上面的这段代码中,来自作为课程一部分的不同视频,在第 10 行,他写道:Base{x}他说他正在委托 Base 类的构造函数,这是我很困惑的地方,因为他使用了大括号在第 14 行,他写道:Base(other)他说他正在委托基类的复制构造函数,他在这里使用了括号,所以我很困惑.... 使用括号或大括号重要吗? 编译器如何知道他是指复制构造函数还是普通的 args 构造函数?

这是你需要的基类

private:
    int value;
public:
   Base()
        : value {0}  { 
            cout << "Base no-args constructor" << endl; 
    }
    Base(int x) 
        : value {x} { 
            cout << "int Base constructor" << endl;
    }
    Base(const Base &other) 
        : value {other.value} {
         cout << "Base copy constructor" << endl;     
    }
        
    Base &operator=(const Base &rhs)  {
    cout << "Base operator=" << endl;
        if (this == &rhs)
            return *this;
        value = rhs.value;
        return *this;
    }
            
   ~Base(){ cout << "Base destructor" << endl; }
};

这是派生类

private:
    int doubled_value;
public:
    Derived() : 
        Base {}  {
            cout << "Derived no-args constructor " << endl; 
    }
    Derived(int x) 
        : Base{x} , doubled_value {x * 2} { 
            cout << "int Derived constructor" << endl; 
    }
    Derived(const Derived &other)
        : Base(other), doubled_value {other.doubled_value} {
         cout << "Derived copy constructor" << endl;     
    }
    
    Derived &operator=(const Derived &rhs) {
            cout << "Derived operator=" << endl;
        if (this == &rhs)
            return *this;
        Base::operator=(rhs);
        doubled_value = rhs.doubled_value;
        return *this;
    }
   ~Derived(){ cout << "Derived destructor " << endl; } 
};

标签: c++

解决方案


不。

括号的选择并不决定您是否委托给另一个构造函数。

括号的选择不是完全随意的,它可以对某些事情产生影响,但不是为了这个。

不幸的是,代码的作者选择了混淆初始化样式,甚至没有写注释来解释他们这样做的原因。


推荐阅读