我最近重構的代碼是這樣的(MyClass
到MyClassR
)。重載函數調用一個參數,但我想我已經通過了兩個
#include <iostream>
class SomeMember
{
public:
double m_value;
SomeMember() : m_value(0) {}
SomeMember(int a) : m_value(a) {}
SomeMember(int a, int b)
: m_value(static_cast<double>(a)/3.14159 +
static_cast<double>(b)/2.71828)
{}
};
class MyClass
{
public:
SomeMember m_first, m_second, m_third;
MyClass(const bool isUp, const int x, const int y)
{
if (isUp)
{
m_first = SomeMember(x);
m_second = SomeMember(y);
m_third = SomeMember(x, y);
}
else
{
m_first = SomeMember(y);
m_second = SomeMember(x);
m_third = SomeMember(y, x);
}
}
};
class MyClassR
{
public:
SomeMember m_first, m_second, m_third;
MyClassR(const bool isUp, const int x, const int y)
: m_first(isUp ? x : y)
, m_second(isUp ? y : x)
, m_third(isUp ? x, y : y, x)
{
}
};
int main()
{
MyClass a(true, 1, 2);
MyClassR b(true, 1, 2);
using namespace std;
cout.precision(10);
cout
<< "a:" << endl
<< "\tfirst: " << a.m_first.m_value
<< "\tsecond: " << a.m_second.m_value
<< "\tthird: " << a.m_third.m_value << endl;
cout
<< "b:" << endl
<< "\tfirst: " << b.m_first.m_value
<< "\tsecond: " << b.m_second.m_value
<< "\tthird: " << b.m_third.m_value << endl;
return 0;
}
- 什麼是錯誤,
- 爲什麼它編譯(用VC6 以及VC9警告級別4測試:無投訴)和
- 是什麼做的正確方法?
我(假設)我已經有了所有這些答案,但我認爲這是分享的有趣和有趣的問題。
更新
擴展代碼,因此它的 「複製粘貼& &執行」 -able。 VC9也沒給我投訴,所以這裏VC6不是問題。
爲了完整起見,輸出爲:
a:
first: 1 second: 2 third: 1.054069532
b:
first: 1 second: 2 third: 1.004499999
我看不到任何錯誤原因。它絕對精細並編譯,按預期執行 – mukeshkumar
人工,修辭問題。建議關閉它。 – Suma
@Suma由於簡化,代碼是人造的。這個問題真的發生了...... – foraidt