int main(int argc, char** argv) { IntCell arr[3]; // read three numbers int input; for (int i = 0; i < 3; i++) { cin >> input; arr[i] = IntCell(input); } // print the numbers forwards and backwards cout << arr[0].read() << " " << arr[1].read() << " " << arr[2].read() << endl; cout << arr[2].read() << " " << arr[1].read() << " " << arr[0].read() << endl; // find min, max and total IntCell total = IntCell(0); IntCell min = arr[0], max = arr[0]; for (int i = 0; i < 3; i++) { if (arr[i].read() > max.read()) max = arr[i]; if (arr[i].read() < min.read()) min = arr[i]; total = total.add(arr[i]); } cout << "max: " << max.read() << endl; cout << "min: " << min.read() << endl; cout << "avg: " << (float)total.read() / 3.0 << endl; return 0; }
/* * Figure 1.15. */ int f( ) { IntCell a( 2 ); IntCell b = a; IntCell c; c = b; a.write( 4 ); cout << a.read( ) << endl << b.read( ) << endl << c.read( ) << endl; return 0; }
int main() { IntCell m; IntCell n; m.write(5); n.write(2); IntCell o = m + n; IntCell p = m - n; cout << "Cell contents m: " << m << endl; cout << "Cell contents n: " << n.read() << endl; cout << "Cell contents o: " << o.read() << endl; cout << "Cell contents p: " << p.read() << endl; return 0; }
int main( ) { IntCell m; // Or, IntCell m( 0 ); but not IntCell m( ); m.write( 5 ); std::cout << "Cell contents: " << m.read( ) << std::endl; return 0; }
int main( ) { IntCell m; m.write( 5 ); std::cout << "Cell contents: " << m.read( ) << std::endl; return 0; }
int main() { IntCell obj; /* 使用explicit意味着单参数构造函数不能用来创建隐式临时对象 * 编译以下两句会得到如下错误 * note: candidate function (the implicit copy assignment operator) * not viable: no known conversion from 'int' to 'const IntCell' for 1st argument */ // obj = 37; obj.write(666); std::cout << obj.read() << "\n"; return 0; }
} const IntCell& IntCell::operator= (const IntCell& rhs) { if (this != &rhs) { *m_storedValue = *rhs.m_storedValue; } return *this; } int IntCell::read() const { return *m_storedValue; } void IntCell::write(int value) { *m_storedValue = value; } TEST_CASE("Class created", "[class]") { IntCell m1(1); REQUIRE(m1.read() == 1); m1.write(2); REQUIRE(m1.read() == 2); IntCell* pm2 = NULL; REQUIRE(pm2 == NULL); pm2 = new IntCell(2); REQUIRE(pm2->read() == 2); delete pm2; }