c++ - 使用大括号和圆括号
问题描述
所以我正在做一个初学者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# - 点击 Geckofx 网络浏览器内的链接将触发 Winforms 中的方法
- android - Android WebView:手机锁定时音频断断续续
- python - 如何比较列表的两个元素以找到最低价格?
- php - 我网站上的这个 PHP 代码有什么作用?
- asp.net - 单击一个 asp:hyperlink 控件将所有 asp:hyperlinks 更改为访问的颜色
- node.js - Heroku 和 NameCheap 上的 API 服务器
- java - 给定 2 个字符串和整数 k,以 k 步将一个字符串转换为另一个字符串
- python - 在 matplotlib 的子图中使用 xscale 和 yscale
- java - 为什么我的 JAR 的 Maven 依赖项没有包含在我的 WAR 中?
- python - 带有XGBoost的Cox PH模型,如何获得生存时间?