[英]Calling a constructor in C++
我只是從C ++開始。 我有一個類ourVector,在該類中,我也有一個名為ourVector()的構造函數,它包含變量的初始化。 我需要這些變量在main中的每個循環中重置,但是我不知道如何在main中調用構造函數。
class ourVector
ourVector()
{
vectorCap = 20;
vectorSize = 0;
}
總的來說,我的類對象稱為ourVector vectorTest;
我只是想弄清楚如何在不出錯的情況下調用ourVector(),因此可以將其放在main循環的末尾,以清除並重新初始化變量。
任何幫助將不勝感激。
謝謝!
通常,當您發現自己在做這樣的事情時,這表明可能存在一種在語義上更合適的方式來構造代碼(即使代碼結構更緊密地表達您的意圖)。
對於您自己的情況,請問自己為什么每次循環都需要重置該值。 似乎您只是在使用對象在循環中的每次迭代中保存一些中間數據,並且您不必擔心循環外的值(但如果您願意,則需要使用riderBill的答案 )。 所以確實,您的ourVector
實例僅在該循環范圍內有用。
因此,使您的代碼結構反映出:
int main () {
...
while (...) { // <- this represents your loop
ourVector v; // <- each time through, 'v' is constructed
... // <- do whatever with 'v' here
} // <- that 'v' goes away when it goes out of scope
...
}
換句話說,只需在它所屬的循環中聲明它即可。 從語義上講,這很有意義(它表示您實際使用該對象的方式和位置),並且無需修改ourVector
即可完成您想要的ourVector
。
通常,作為
初學者的
經驗法則,請嘗試在仍適用於您的代碼的盡可能狹窄的范圍內聲明變量。
僅在實例化對象時才調用構造函數。 您不能顯式調用它來重新初始化變量。 但是您可以從構造函數中調用public成員setter函數。 然后,您可以在循環中再次調用setter函數。
class ourVector
{ int vectorCap ;
int const defaultVectorCap = 20; // No magic numbers!
int vectorSize ;
int const defaultVectorSize = 0;
int roomToGrow ; // To illustrate a point about setters.
public:
// Constructors
ourVector() // Use this constructor if you don't know the proper initial values
// (you probably always do or never do).
{ setVectorCap (defaultVectorCap );
setVectorSize(defaultVectorSize);
} // End of default constructor
ourVector( int vecCap, int vecSize) // Lining stuff up improves readability
{ setVectorCap (vecCap ); // (e.g. understanding the code and
setVectorSize( vecSize ); // spotting errors easily).
// It has helped me spot and avoid
// bugs and saved me many many hours.
// Horizontal white space is cheap!
// --Not so forvertical white space IMHO.
// Setters
void setVectorCap(int vecCap)
{ vectorCap = vecCap;
// I might need this internally in the class.
// Setters can do more than just set a single value.
roomToGrow = vectorCap - vectorSize;
} // End of setVector w/ parameter
void setVectorSize(int vecSize)
{ vectorSize = vecSize;
roomToGrow = vectorCap - vectorSize; // Ok, redundant code. But I did say
// "As much as practical...."
} // End of setVectorCap w/ parameter
void setVectorSize() // Set to default
{ // Don't just set it here--leads to poor maintainability, i.e. future bugs.
// As much as practical, redundant code should be avoided.
// Call the setter that takes the parameter instead.
setVectorSize(defaultVectorSize);
} // End of setVectorSize for default size
void setVectorCap() // Set to default
{ setVectorCap (defaultVectorCap );
} // End of setVectorCap for default size
}; // End of class ourVector
#include <cstdio>
#include <cstdlib>
#include "ourVector.hpp"
int main(int argc, char *argv[]);
void doSomething(ourVector oV );
int main(int argc, char *argv[])
{ ourVector oV;
// Or, if you want non-default values,
//int mySize = 2;
//int myCap = 30;
//ourVector(mySize, myCap);
for (int i = 0; i<10; i++)
{ // Set fields to original size.
oV.setVectorSize();
oV.setVectorCap ();
// Or
//oV.setVectorSize(mySize);
//oV.setVectorCap (myCap );
// Whatever it is your are doing
// ...
}
// Do whatever with your vector. If you don't need it anymore, you probably should
// have instantiated it inside the for() block (unless the constructor is
// computationally expensive).
doSomething(oV);
return 0;
} // End of main()
void doSomething(ourVector oV) {}
此代碼有效:
class ourVector
{
public:
ourVector() : vectorCap(20), vectorSize(0) { };
ourVector(int c, int s) : vectorCap(c), vectorSize(s) { };
void setVCap(int v)
{
vectorCap = v;
}
void setVSize(int v)
{
vectorSize = v;
}
int getVCap()
{
return vectorCap;
}
int getVSize()
{
return vectorSize;
}
void print()
{
std::cout << vectorCap << ' ' << vectorSize << '\n';
}
private:
int vectorCap;
int vectorSize;
};
int main()
{
ourVector vectorTest(5,5);
vectorTest.print();
vectorTest.setVCap(6);
vectorTest.setVSize(6);
vectorTest.print();
std::cout << vectorTest.getVCap() << ' ' << vectorTest.getVSize() << '\n';
vectorTest = ourVector();
vectorTest.print();
}
ourVector() : vectorCap(value), vectorSize(value) { };
零件是初始化器。 vectorCap(value)
部分將vectorCap
設置為value
; { }
部分是一個空方法,使用它可以進行所需的任何計算和驗證。 可以調用SetVCap(int)
和SetVSize(int)
方法分別更改vectorCap
和vectorSize
的值。 getVCap()
和getVSize()
返回vectorCap和vectorSize的值。
在我的示例中,您不需要驗證代碼,因此初始化程序ourVector() : vectorCap(value), vectorSize(value) { };
工作完美。 如果需要驗證輸入,則可能希望從初始化程序中調用賦值函數,因此只需要執行一次驗證,這使調試更加容易。 為此,只需將這些構造函數替換為這些構造函數即可。 現在,您只需要在一個地方驗證輸入:
ourVector()
{
setVCap(20);
setVSize(0);
}
ourVector(int c, int s)
{
setVCap(c);
setVSize(s);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.