![](/img/trans.png)
[英]C++ parameterized constructor makes code to stop working when large input's are passed
[英]Working of parameterized constructor in C++ when variables are initailized vs uninitialized
以下 C++ 代碼有效。
#include<iostream>
using namespace std;
class Complex{
private:
int real, imag;
public:
Complex(int r=0, int i=0){
real = r; imag = i;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3;
}
當參數化構造函數的變量r
和i
未初始化時(例如: Complex(int r, int i)
),編譯器會拋出錯誤
main.cpp:19:13: 錯誤:沒有匹配的 function 調用 'Complex::Complex()' 19 | 復雜的c3; | ^~ main.cpp:10:5: 注意:候選:'Complex::Complex(int, int)' 10 | 復雜(int r,int i){ | ^~~~~~~。
我理解這是Complex c3;
. 請原諒我的天真,但不清楚為什么它在初始代碼片段本身中以這種方式工作。 希望有人能澄清這一點。
您顯示的Complex
構造函數默認為 arguments,可以使用兩個、一個或零 arguments 調用。如果未使用 arguments,則將使用默認值。
但是如果你去掉默認值,你就不再有默認的構造函數,一個不用arguments就可以使用的構造函數。
它實際上與具有默認參數值的普通函數完全相同......
假設您有這個 function:
void foo(int arg = 0)
{
// Implementation is irrelevant
}
現在這可以稱為:
foo(123); // Pass an explicit argument
或者作為:
foo(); // Equivalent to foo(0)
如果刪除默認值:
void foo(int arg)
{
// Implementation is irrelevant
}
然后不帶任何參數調用 function 是錯誤的:
foo(); // Error: Argument expected
Complex(int r=0, int i=0)
的定義允許 0、1 或 2 個參數。 Complex c3;
正在構造一個參數為 0 的Complex
。
您可以改用重載,例如
class Complex{
private:
int real, imag;
public:
Complex() : real(0), imag(0) {}
Complex(int r, int i) : real(r), imag(i) {}
};
請注意,最好使用成員初始化程序而不是構造函數主體中的賦值語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.