https://github.com/haotang923/interview/tree/master/IKM

  • Q1. If most of the calls to function foo() below pass one of 10 particular values, which method will significantly reduce the execution time of calling the function?
  • A. Replace * with an if-else block testing for the 10 values, assigning r accordingly
  • B. Remove inline
  • C. Delete foo() and move the time-consuming operation to its caller
  • D. Replace * with code performing a table lookup, with the 10 values and corresponding values of r
  • E. Replace * with swtich
  • A1. D ?
 inline int foo (int x) {
int r; * // time-consuming operation on x, result stored in r return r;
}

 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
// #include <iostream>
using namespace std; class SomeClass {
public:
static int data;
}; /*
The declaration of a static data member in the member list of a class is not a definition. You must define the static member outside of the class declaration, in namespace scope.
*/
int SomeClass::data = ; // Definition or redeclaration of 'data' not allowed inside a function (including the main function) SomeClass objSome; int main(int argc, char* argv[])
{
/*
0
0
*/
cout << SomeClass::data << endl;
cout << objSome.data << endl; // cout << SomeClass<static int>.data << endl;
// cout << objSome->data << endl;
// cout << SomeClass::objSome.data << endl;
// cout << objSome::data << endl; return ;
}

  • Q3. When must a C++ destructor be declared virtual in a base class?
  • A. virtual default constructor of base class
  • B. derived class allocates system resources which are released in its destructor
  • C. the destructor of the base class will clean up the derived class data
  • D. implementation for the derived class destructor is not desired
  • E. ensure that a derived class destructor is invoked when an instance is destroyed through a base class pointer
  • A3. E ?

  • Q4. Complete code to perform a categorization of the letter type.
  • stringstream::stringstream - C++ Reference
    • http://www.cplusplus.com/reference/sstream/stringstream/stringstream/
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
// #include <string>
#include <vector>
#include <sstream>
using namespace std; int main(int argc, char* argv[])
{
enum letterType {complement, complaint, unknown}; string letter = "happy sad happy sad sad";
string sHappy = "happy";
string sSad = "sad"; pair<string, int> happy = make_pair(sHappy, );
pair<string, int> sad = make_pair(sSad, ); string word;
stringstream ss(letter);
vector<string> letterWords;
while (ss >> word) letterWords.push_back(word); vector<string>::iterator words;
for (words = letterWords.begin(); words < letterWords.end(); words ++) {
word = *words; /*
Following 2 lines is the answer
*/
if (happy.first.find(word) != string::npos) happy.second ++;
if (sad.first.find(word) != string::npos) sad.second ++;
} /*
1
*/
if (happy.second > sad.second) return complement;
else if (happy.second < sad.second) return complaint;
else return unknown;
}

  • Q5. Modify code to correctly access the member Driver to compiler error
  • A. Derive a class from Bus. Make the object driver a dedrived class pointer.
  • B. Make the function createDriver() non-static.
  • C. Declare the function useBus() to be a friend of class Bus.
  • D. Change the access level of member Driver to public
  • E. Make the function createDriver() return a Driver& then make the object driver a reference object.
  • A5. CD
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Bus {
protected:
class Driver; // forward declarations public:
static Driver* createDriver() {
return new Driver;
} // friend void useBus(); private:
int seats;
protected:
class Driver {
public:
string name;
};
}; class DeriveDriver : public Bus {}; void useBus()
{
Bus::Driver* driver = Bus::createDriver(); // 'Driver' is a protected member of 'Bus'
// DeriveDriver::Driver* driver = Bus::createDriver(); // 'Driver' is a protected member of 'Bus' driver->name = "DRIVER";
} int main(int argc, char* argv[])
{
return ;
}

  • Q6. Which are legal calls to the function template?
  • A. double output = power<int, 100>(3.0, 'a');
  • C. double output = power<int, 500>(3.0, 100);
  • A6. AC
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; template <typename T, int duration>
double power (double amplitude, int frequency = ) { return amplitude * frequency; } int main(int argc, char* argv[])
{
double output; output = power<int, >(3.0, 'a');
// output = power<500>(3.0); // No matching function for call to 'power'
output = power<int, >(3.0, );
// output = power<int>(3.0, 100); // No matching function for call to 'power'
// output = power<int, char>(3.0); // No matching function for call to 'power'
output = power<int, >(3.0); cout << output << endl; return ;
}

  • Q7. Which are NOT elements of exception processing in C++?
  • A. Making an exception specification using throw()
  • B. Using dynamic_cast<> on references
  • C. Using assert ()
  • D. Making an exception specification using noexcept
  • E. Throwing an object of class Exception
  • A7. C ?
  • C++ 异常处理 | 菜鸟教程
    • http://www.runoob.com/cplusplus/cpp-exceptions-handling.html
  • bad_cast thrown by dynamic_cast when it fails in a dynamic cast
    • Exceptions - C++ Tutorials

      • http://www.cplusplus.com/doc/tutorial/exceptions/
  • Exceptions and asserts are two distinct mechanisms for detecting run-time errors in a program.
    • https://msdn.microsoft.com/en-us/library/hh279678.aspx

  • Q8. Which are correct declarations for a copy constructor for a class named Gizmo?
  • D. Gizmo(const Gizmo& v);
  • E. Gizmo(const Gizmo&);
  • A8. DE
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Gizmo{
Gizmo();
~Gizmo(); // declaration goes here
// Gizmo(const Gizmo* copy_me) const; // 'const' qualifier is not allowed on a constructor // Gizmo(const Gizmo&) const; // 'const' qualifier is not allowed on a constructor // Gizmo(Gizmo& const copy_me); // 'const' qualifier may not be applied to a reference Gizmo(const Gizmo& v); Gizmo(const Gizmo&);
}; int main(int argc, char* argv[])
{
return ;
}

  • Q9. Which are true about C++ inheritance access specifications?
  • A. Protected inheritance from the base class makes all of the base class members protected in the derived class.
  • B. Dynamic inheritance from the base class allows derived class member's access control to be changed on the fly.
  • C. Public inheritance from the base class makes all of the base class members public in the derived class.
  • D. Private inheritance from the base class makes all of the base class members private in the derived class.
  • E. Private members in the base class are not changed via the inheritance access specifications.
  • A9. E ?

  • Q10. Which correctly describe C++ references?
  • A. A reference may refer to a different object by assignment.
  • B. A reference creates an alias to another object.
  • C. A reference remains valid irrespective of the scope or lifetime of the referenced object.
  • D. The operator -> must be used to access the referenced object.
  • E. A reference must be initialized when it is declared.
  • A10. BE ?

  • Q11. Which C++ code contain problems?
  • A11. DE
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; int getLength() {
return ;
} int size = getLength();
// char message[size]; // Variable length array declaration not allowed at file scope int main(int argc, char* argv[])
{
bool ok = true; if (!ok) {
cout << "not ok" << endl;
} const int size = ;
char message[size]; int numerator, denominator; numerator = 10.0;
denominator = 3.0; float quotient = numerator / denominator; // signed char scope is -128 ~ 127
for (char idx = ; idx < ; idx ++) { // Comparison of constant 250 with expression of type 'char' is always true
cout << "hello world" << endl;
} return ;
}

  • Q12. Which regarding the C++ 11 operators alignof() and alignas() are correct?
  • A. alignof () is used to obtain the alignment of a specified variable or type.
  • B. alignas () is used to specify custom alignment of variables and user-defined types.
  • C. alignas () returns the size, in bytes, of the expression in parentheses.
  • D. alignof () returns the size, in bytes, of the expression in parentheses.
  • E. alignas () works on expressions.
  • A12. ABE ?

  • Q13. Which legal for-loop syntax in C++?
  • A13. ABD
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; int main(int argc, char* argv[])
{
for (double d = 1.0; d <= 1.9; d += 0.1)
cout << "testA" << endl; for (int i = ; i; i --)
cout << "testB" << endl; // for (true) // Expected ';' in 'for' statement specifier
cout << "testC" << endl; for (; ;)
cout << "testD" << endl; // for (int i = 0, i < 10, i ++) // Redefinition of 'i'
cout << "testE" << endl; return ;
}

  • Q14. When using the multi-threading library in the C++ standard library, which are NOT callable objects which may be run in a thread?
  • A. A class with an overridden operator()
  • B. A class member function
  • C. A lambda function
  • D. An executable file
  • E. A regular function
  • A14. D ?
  • C++语言有几种callable objects:函数、函数指针、lambda表达式、bind创建的对象以及重载了函数调用运算符()的类。

  • Q15. Which are true regarding the C++ code segment below?
  • A. The variable numCities accurately reflects the number of complete State/Capital-city pairs.
  • B. After the initial 3 insertions, the map will be sorted such that the pair containing Albany will be the first entry.
  • C. The two lines indicated by the comment Alteration 2 are attempting to do something that is not allowed in C++.
  • D. The two lines indicated by the comment Alteration 1 is a valid way to find and alter this State/Capital-city pair.
  • E. The variable numStates accurately reflects the number of complete State/Capital-city pairs.
  • A15. CE
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <string>
#include <map>
using namespace std; int main(int argc, char* argv[])
{
map<string, string> capitals;
map<string, string>::iterator it;
string west = "California";
size_t numCities, numStates; capitals.insert(make_pair ("NewYork", "Albany")); // misspelled
capitals.insert(make_pair("Texas", "Houston")); // wrong city
capitals.insert(make_pair("California", "Sacramento")); for (auto &i : capitals) {
cout << i.first << " " << i.second << endl;
} cout << endl; numCities = capitals.count(west); cout << "numCities = " << numCities << endl;
cout << endl; it = capitals.find("Houston"); // Alteration 1
it->second = "Austin"; // Alteration 1 for (auto &i : capitals) {
cout << i.first << " " << i.second << endl;
} cout << endl; it = capitals.find("NewYork"); // Alteration 2
// No viable overloaded '='
// it->first = "New York"; // Alteration 2 string ILcap = capitals["Illinois"];
numStates = capitals.size(); for (auto &i : capitals) {
cout << i.first << " " << i.second << endl;
} cout << endl; cout << "ILcap = " << ILcap << endl;
cout << "numStates = " << numStates << endl; return ;
}

  • Q16. Which correctly describe the overloading of the comparison operator in the C++ code fragment below?
  • A. The < operator overloading is not needed. Use the default implementation.
  • B. The < operator has the wrong return type.
  • C. The < operator may not be overloaded.
  • D. The < operator is implemented correctly as is.
  • E. The < operator will not be accessible to code using an object of type x.
  • A16. BC ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class x {
x& operator< (const x& rhs) const {
int thisVol = height * width * length;
int thatVol = rhs.height * rhs.width * rhs.length; // Non-const lvalue reference to type 'x' cannot bind to a temporary of type 'bool'
return thisVol < thatVol;
}
/*
bool operator< (const x& rhs) const {
int thisVol = height * width * length;
int thatVol = rhs.height * rhs.width * rhs.length; return thisVol < thatVol;
}
*/
private:
int height;
int length;
int width;
}; int main(int argc, char* argv[])
{
return ;
}

  • Q17. Which of the following describe situations in which the C++ compiler generates a default constructor for a class?
  • A. When a compiler switch is used to instruct the C++ compiler to generate the default constructor
  • B. When the class has no default constructor defined
  • C. When the class has declared a virtual constructor
  • D. When the class has no constructor defined or deleted
  • E. When the C++ compiler needs to construct a temporary object of the class
  • A17. D ?

  • Q18. Which are C++ declarations of pointer variables (defined elsewhere) which cannot be changed (cannot be made to point to anything else)?
  • A. extern float* const ptr;
  • B. extern const std::vector<int>* ptr;
  • C. extern const void* ptr;
  • D. extern const int* const ptr;
  • E. extern double* ptr const;
  • A18. AD

  • Q19. Which represent a valid declaration for the code below for overloading the array subscript operator that returns int& in C++?
  • A. int& operator()(int);
  • B. int& operator[int](int);
  • C. int& operator[int]();
  • D. int& operator(int)();
  • E. int& operator[](int);
  • A19. E
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class MyArray {
public:
// declaration goes here
int& operator()(int);
// int& operator[int](int); // Expected ']'
// int& operator[int](); // Expected ']'
// int& operator(int)(); // Expected ')'
int& operator[](int);
}; int main(int argc, char* argv[])
{
return ;
}

  • Q20. Which correctly describe C++ code optimization?
  • A. It is the phase of generation of an executable program during which library function references are resolved.
  • B. It is the process of modifying source code to enhance some aspect of its execution, usually at the expense of other aspects.
  • C. It is the process of tailoring machine code generated during compilation so that the resultant code runs more quickly or efficiently.
  • D. It refers to the collection and precompilation of header files for more efficient processing at compile time.
  • E. It is the process of capturing the required aspects of a software package before the source code is written.
  • A20. B ?

  • Q21. Which can be the results of executing the C++ code fragment below?
  • A. An error because member code is a char.
  • B. An output of "B".
  • C. Undefined results.
  • D. An output of "65".
  • E. Unspecified (implementation-dependent) results.
  • A21. D
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class base {
public:
base() : code('B') { }
char code;
}; class derived : public base
{
public:
int code;
}; int main(void)
{
derived d;
d.code = ;
std::cout << d.code;
};

  • Q22. Which, when substituted for ***** in the C++ program below, will output "0 1 2 3 4 5 6 7 8 9 10 11" ?
  • E. iota( ++sequence.begin(), sequence.end(), 1 );
  • A22. E
  • http://www.cplusplus.com/reference/numeric/iota/
  • http://www.cplusplus.com/reference/utility/move/?kw=move
  • http://www.cplusplus.com/reference/algorithm/copy_if/?kw=copy_if
  • http://www.cplusplus.com/reference/algorithm/for_each/?kw=for_each
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <vector>
#include <numeric> // std::iota
#include <utility> // std::move
#include <algorithm> // std::copy_if, std::for_each
using namespace std; int main()
{
std::vector<int> sequence{ , , , , , , , , , , , }; /*****/ // 1 2 3 4 5 6 7 8 9 10 11 12
// iota( sequence.begin(), sequence.end(), 1 ); // 0 1 1 0 1 5 8 13 21 34 55 89
// move( sequence.begin(), sequence.begin() + 2, sequence.begin() + 3 ); // 0 1 1 1 1 1 1 1 1 1 1 1
// for_each( sequence.begin(), sequence.end(),
// []( int& elem ) { if ( elem > 1 ) elem = 1; } ); // 0 1 1 0 1 5 8 13 21 34 55 89
// copy_if( sequence.begin (), sequence.begin() + 2, sequence.begin() + 3,
// []( int elem ) { return elem <= 1; } ); // 0 1 2 3 4 5 6 7 8 9 10 11
iota( ++sequence.begin(), sequence.end(), ); // Print out the modified sequence -- what will it be?
for( int elem : sequence )
{
std::cout << elem << " ";
} std::cout << std::endl; return ;
}

  • Q23. Which are types of polymorphism in C++?
  • A. Bi-metric polymorphism
  • B. Hybrid polymorphism
  • C. Parametric polymorphism
  • D. Post processing polymorphism
  • E. Single polymorphism
  • A23. C
  • The Four Polymorphisms in C++ :
    • http://www.catonmat.net/blog/cpp-polymorphism/
    • Subtype polymorphism is also known as runtime polymorphism.
    • Parametric polymorphism is also known as compile-time polymorphism.
    • Ad-hoc polymorphism is also known as overloading.
    • Coercion is also known as (implicit or explicit) casting.

  • Q24. Which if substituted for ***** will be illegal?
  • C. bObj.weight = 110;
  • A24. C
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class A {
public:
int age;
int weight;
protected:
int iq;
}; class B : protected A {
public:
using A::iq;
using A::age;
}; class C : private B {
public:
using B::iq;
using B::weight;
}; int main()
{
B bObj;
C cObj; /*****/ bObj.iq = ;
cObj.iq = ;
// bObj.weight = 110; // Cannot cast 'B' to its protected base class 'A'
bObj.age = ;
cObj.weight = ; return ;
}

  • Q25. Which are valid when using multi-threading library that is part of the C++ STL?
  • A. Multiple threads of a single program have no way of communicating with each other.
  • B. Multi-threading requires proprietary libraries.
  • C. Multiple threads of a single program may share the same resources.
  • D. Multi-threading is not possible on a computer with a single CPU containing a single core.
  • E. Multi-threading is an ability to create a process that consists of multiple threads of execution (the smallest sequence of programming instructions that can be managed independently by a scheduler).
  • A25. CE ?

  • Q26. Which changes to the C++ code snippet below are required for it to compile?
  • A. Change the line at location #1 to: controllers::spin(false);
  • B. Change the line at location #1 to: rotary::spin(false);
  • C. Change the line at location #2 to: controllers::horizontal::move(true);
  • D. Change the line at location #2 to: horizontal::move(true);
  • E. Change the line at location #1 to: horizontal::spin(false);
  • A26. B
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; namespace controllers {
namespace rotary {
void spin(bool start) {
if (!start) { }
}
} namespace horizontal {
void move(bool start) {
if (start) {
// Use of undeclared identifier 'spin'; did you mean 'rotary::spin'?
// spin(false); // location #1 // No member named 'spin' in namespace 'controllers'; did you mean 'rotary::spin'?
// controllers::spin(false); rotary::spin(false); // No member named 'spin' in namespace 'controllers::horizontal'; did you mean 'rotary::spin'?
// horizontal::spin(false);
}
}
}
} int main(int argc, char **argv)
{
// move(true); // location #2 // controllers::horizontal::move(true); // Use of undeclared identifier 'horizontal'; did you mean 'controllers::horizontal'?
// horizontal::move(true);
}

  • Q27. Which are valid ways to create a type alias?
  • A. template<class T> using vec = std::vector<T>; vec<float> incomes;
  • C. typedef int intAlias; intAlias count;
  • E. template<typename T> using myGenric = T; myGenric<int> age;
  • A27. ACE
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std; template<class T> using vec = std::vector<T>;
vec<float> incomes; /*
typedef std::vector<T> vec; // Use of undeclared identifier 'T'
vec<double> weights;
*/ typedef int intAlias;
intAlias count; /*
typedef T genricAlias<T>; // Unknown type name 'T'
genricA1ias<int> population;
*/ template<typename T> using myGenric = T;
myGenric<int> age; int main(int argc, char **argv)
{
}

  • Q28. Which are correct statements about C++ exception handling?
  • A. The most general catch block exception should appear last, with increasingly more specific catch block exceptions preceding it.
  • B. An exception handler with no exception parameter - such as catch() - will catch any exception regardless if matching catch blocks also exist.
  • C. Multiple classes can be caught in a single catch clause as multiple arguments.
  • D. Exceptions not matching other catch blocks may be caught and handled by a handler specified by catch (…)
  • E. An exception is routed to the most appropriate/matching catch block regardless of the order the catch blocks appear.
  • A28. AD ?

  • Q29. Given the array of pointers to C++ function, which are correct declaration for the function processor()?
  • A. double processor(int i, double(*f), int idx);
  • B. double processor(int i, double(*f(int)), int idx);
  • C. double processor(int i, double(*f)(int), int idx);
  • D. double processor(int i, double(*f[]), int idx);
  • E. double processor(int i, double(f[])(), int idx);
  • A29 ?

  • Q30. Which of the following statements are true with respect to C++ code excerpt below?
  • A. a6 is a const reference to a3.
  • B. d5 is an int initialized to 5.
  • C. al is an instance of class auto, instantiated by an integer value of "5" being passed to a constructor.
  • D. a2 is an int equal to 10.
  • E. d4 is an int initialized to 10.
  • A30. BD ?
  • auto (C++) | Microsoft Docs
    • https://docs.microsoft.com/en-us/cpp/cpp/auto-cpp
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <typeinfo> // std::typeid
using namespace std; int somFunc() { return ; } int main(int argc, char **argv)
{
auto a1 = ;
auto a2 = somFunc(); decltype(a2) d4;
decltype(somFunc()) d5 = ; double a3 = 4.0;
auto &a6 = a3; cout << typeid(a1).name() << endl;
cout << typeid(a2).name() << endl;
cout << typeid(d4).name() << endl;
cout << typeid(d5).name() << endl;
cout << typeid(a3).name() << endl;
cout << typeid(a6).name() << endl;
}

  • Q31. Which are member functions of a C++ STL container class which return an iterator to the first element in the container?
  • A. start()
  • B. iterator()
  • C. _first()
  • D. begin()
  • E. bof()
  • A31. D

  • Q32. Which can be used to replace the ***** in the C++ code excerpt below to create a 10x5 rectangular array of doubles on the heap?
  • A. dArray[r] = new double*;
  • B. dArray[r] = new double[columns];
  • C. dArray[r] = new double;
  • D. *dArray[r] = new double[columns];
  • E. dArray[r] = new double*[columns];
  • A32. B
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; int main(int argc, char **argv)
{
int rows = ;
int columns = ; double **dArray = new double*[rows]; for (int r = ; r < rows; r ++) {
/*****/ // Assigning to 'double *' from incompatible type 'double **'; dereference with *
// dArray[r] = new double*;
dArray[r] = new double[columns];
dArray[r] = new double;
// Assigning to 'double' from incompatible type 'double *'; dereference with *
// *dArray[r] = new double[columns];
// Assigning to 'double *' from incompatible type 'double **'; dereference with *
// dArray[r] = new double*[columns];
}
}

  • Q33. Which of the following correctly describe the purpose of the C++ Standard Library numeric_limits type?
  • A. It is a type that specifies the limits of various resources a program has including memory, storage space and CPU time.
  • B. It is a type that is used to designate actions to be taken when variables exceed their limits.
  • C. It is a template which is specialized for basic types designating the upper and lower limits for those on the current platform.
  • D. It is used to set limits on numeric variables, beyond which an exception will be generated.
  • E. It is used to set the upper and lower limits a variable may have.
  • A33. C ?
  • numeric_limits - C++ Reference
    • http://www.cplusplus.com/reference/limits/numeric_limits/
  • numeric_limits Class | Microsoft Docs
    • https://docs.microsoft.com/en-us/cpp/standard-library/numeric-limits-class

  • Q34. Which are true about the declarations representing the C++ class hierachy below?
  • A. Level5::func2(int) will override any functionality defined in Level2::func2(int).
  • B. Level1::func1() functionality has been removed from Level2 but is still available to subsequent levels.
  • C. Level5::func4(char) will produce a compiler error since it is not a true override.
  • D. Level5::func3(int) will produce a compiler error since virtual functions implemented elsewhere cannot be deleted.
  • E. Level5 results in a compiler error since it cannot inherit from Levei3.
  • A34. CE ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Level1 {
public:
void func1();
}; class Level2 : public Level1 {
public:
void func1() = delete;
int func2(char);
}; class Level3 final : public Level2 {
public:
virtual double func3(int);
}; class Level4 : public Level2 {
virtual double func4(int);
double func5(char a);
}; class Level5 : public Level3 { // Base 'Level3' is marked 'final'
public:
double func2(char) override; // Only virtual member functions can be marked 'override'
virtual double func3(int) = delete;
virtual double func4(char) override; // 'func4' marked 'override' but does not override any member functions
}; int main(int argc, char **argv)
{
Level3 obj; obj.func1(); // Attempt to use a deleted function return ;
}

  • Q35. Which correctly describe C++11 unordered associative containers, for example std::unordered_set, std::unordered_map, std::unordered multiset, std::unordered—multimap?
  • A. They perform their lookup based on a hash function.
  • B. Lookup has o ( log (n) ) complexity.
  • C. They perform their lookup based on an ordering criterion.
  • D. They are implemented as binary trees.
  • E. All allow multiple entries for the same key.
  • A35.  A ?

  • Q36. Which correctly describe attributes of function overloading in C++ programming?
  • A. The functions have to be nested within a namespace.
  • B. The code of the functions must be different.
  • C. The names of the functions must be different.
  • D. The argument types and/or the number of arguments to the functions must be different.
  • E. The return types from the functions must be different.
  • A36. AD

  • Q37. Immediately after the evaluation of the expression and the assignment of the results to interger variable 'a', which will be correct, regarding the value of 'a'?
  • A. The value of 'a' cannot reliably be known in all cases and environments since the order that x(), y(), z() will be evaluated is not fixed by the standard.
  • E. 13
  • A37. E
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; int b = ; int x() { b ++; return b; }
int y() { b *= ; return b - ; }
int z() { b = b + ; return b + ; } int main(int argc, char **argv)
{
int a = x() - y() + z(); // 2 - 5 + 16 //
cout << a << endl; //
cout << b << endl; return ;
}

  • Q38. Which class types must contain at least one pure virtual function in C++?
  • A. An abstract class
  • B. A mixin class
  • C. A virtual class
  • D. A pure virtual class
  • E. A closure class
  • A38. AD ?
  • A class that contains at least one pure virtual function is considered an abstract class.
    • https://msdn.microsoft.com/en-us/library/c8whxhf1.aspx

  • Q39. Which changes must be made to the C++ code below so it can compile?
  • A.    Remove the constexpr qualifier from Line 5.
  • B.    Remove the constexpr qualifier from Line 2.
  • C.    Add the constexpr qualifier to Line 3.
  • D.    Add the constexpr qualifier to Line 4.
  • E.    Remove the constexpr qualifier from Line 1.
  • A39. A
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Vector {
public:
constexpr Vector( double i, double j, double k ) // Line 1
: ivec( i ), jvec( j ), kvec( k )
{} constexpr Vector( const Vector &rhs ) // Line 2
: ivec( rhs.ivec ), jvec( rhs.jvec ), kvec( rhs.kvec )
{} private:
double ivec, jvec, kvec; // Line 3
}; int main(int argc, char **argv)
{
Vector vec1( , , - ); // Line 4
// constexpr Vector vec2( vec1 ); // Line 5
Vector vec2( vec1 ); // Line 5 return ;
}

  • Q40. When writing a multi-threaded program, using the multi-threading library that is part of the C++ standard library, which are valid regarding threads accessing a shared resource?
  • A. Resource sharing among threads cannot be done safely in all situations and is best avoided.
  • B. When multiple threads are sharing a resource, the order in which the threads access the resource does not matter since they all have their own virtual instance of that resource.
  • C. There are several things the threads must do, in order to safely share a resource.
  • D. If a thread "locks" a resource, that resource is automatically unlocked when the thread terminates.
  • E. When multiple threads are accessing a shared resource, access control is done automatically by the C++ runtime environment and is seamless to the individual threads.
  • A40. C ?

  • Q41. Which are valid C++ expressions for creating and using an alias of a type?
  • A. typedef int MYVAR1; MYVAR1 m1;
  • C. using MYVAR2 = char; MYVAR2 m2; m2 = 'a';
  • A41. AC
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; typedef int MYVAR1;
MYVAR1 m1; // alias MYVAR4 long; // Unknown type name 'alias' using MYVAR2 = char;
MYVAR2 m2; // type MYVAR3 double; // Unknown type name 'type' // typedef MYVAR5 using int; // Unknown type name 'MYVAR5' int main(int argc, char **argv)
{
m2 = 'a'; return ;
}

  • Q42. Given the array of pointers to C++ functions below, which of the following lines may be inserted into the loop at ***** such that successive functions fx(), fy() and fz() are pointed to and executed, one per loop?
  • A. PFvv[i]();
  • B. *functions[i]();
  • C. &functions[i]();
  • D. functions[i]();
  • E. functions[i];
  • A42. DE ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; void fx() {}
void fy() {}
void fz() {} typedef void(*PFvv)();
PFvv functions[] = {fx, fy, fz}; int main(int argc, char **argv)
{
for (int i = ; i < ; i++ ) {
/*****/
// PFvv[i](); // Redefinition of 'i'
// *functions[i](); // Indirection requires pointer operand ('void' invalid)
// &functions[i](); // Cannot take the address of an rvalue of type 'void'
functions[i]();
functions[i];
} return ;
}

  • Q43. Throwing and catching C++ exceptions is an alternative to which techniques?
  • A. Running the program with stack tracing enabled
  • B. Returning error codes
  • C. Using hardware exceptions
  • D. Using assertions
  • E. Exhaustive debugging
  • A43. BD

  • Q44. Which are true about the C++11 compliant program below?
  • A. Line 1 does nothing if NDEBUG is not defined.
  • B. The program compiles normally, but prints the warning message If the collection is empty.
  • C. Line 2 results in a compiler error if the collection is empty.
  • D. Line 2 will cause a compiler error because ">>" will be mistaken for the right-shift operator.
  • E. Line 2 results in a compiler error if type std::vector<int> is not an empty class.
  • A44. E ?
  • static_assert | Microsoft Docs
    • https://docs.microsoft.com/en-us/cpp/cpp/static-assert
  • is_empty Class | Microsoft Docs
    • https://docs.microsoft.com/en-us/cpp/standard-library/is-empty-class
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std; template <typename T>
void processCollection(T t) {
// Static_assert failed "collection is empty"
static_assert(std::is_empty<T>::value, "collection is empty"); // Line 1 // ...
}; int main(int argc, char **argv)
{
std::vector<int> ages; // ... processCollection<std::vector<int>>(ages); // Line 2 return ;
}

  • Q45. Which is a DeMorgan equivalent to the statement below? return !a || !b;
  • A. return !b || !a;
  • B. return !a && !b;
  • C. return a && b;
  • D. return !(a && b);
  • E. return !(a || b);
  • A45. AD

  • Q46. which about std::weak_ptr in C++ are correct?
  • A. An instance can transfer ownership of its contained pointer if assigned to an object of std::unique_ptr.
  • B. The object being referenced by the std::unique_ptr instance must be checked to see if it still exists before it can be accessed.
  • C. Access to an instance's contained pointer is via operator->().
  • D. Each instance does not increase the reference count of the pointer object being shared.
  • E. An instance must be initialized by either an object of std::shared_ptr or another std::weak_ptr object.
  • A46. D ?
  • weak_ptr Class | Microsoft Docs
    • https://docs.microsoft.com/en-us/cpp/standard-library/weak-ptr-class

  • Q47. Which correctly identify the results of building the C++ code below?
  • A. Compiling generates an error because main() is not allowed to access the protected member data of SomeClass.
  • B. The build will be successful, and the program will display an output of "5" when it is executed.
  • C. Compiling generates an error because SomeFunc() is not allowed to access the protected member data of SomeClass.
  • D. Compiling generates an error because Anotherclass is not allowed to declare someFunc() as a friend as it is already a friend of SomeClass.
  • E. Compiling generates an error because Another() of AnotherClass is not allowed to access the protected member data of SomeClass.
  • A47. AC
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class SomeClass {
protected:
int data;
friend class AnotherClass;
}; void SomeFunc(SomeClass sc) {
sc.data = ; // 'data' is a protected member of 'SomeClass'
} class AnotherClass {
public:
void Another(SomeClass sc) {
sc.data = ;
} friend void SomeFunc(SomeClass sc);
}; int main(int argc, char **argv)
{
SomeClass sc;
SomeFunc(sc); cout << sc.data << endl; // 'data' is a protected member of 'SomeClass' return ;
}

  • Q48. Which are true?
  • A. It cannot be assigned to.
  • B. It can be passed to a function by value.
  • C. It cannot be returned from a funtion by value.
  • D. It can be copied.
  • E. Another class can be derived from it.
  • A48. ACE
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class BBus {
int DriverID;
string routeName; BBus(BBus &orig) {
DriverID = orig.DriverID;
routeName = orig.routeName;
} BBus& operator=(BBus &rhs) {
DriverID = rhs.DriverID;
routeName = rhs.routeName;
return *this;
} public:
BBus(int id = , string rt = "") : DriverID(id), routeName(rt) {}
}; class C : public BBus {
public:
void print() {
cout << __func__ << endl;
}
}; void testB(BBus objB) {
cout << __func__ << endl;
} /*
BBus testB2() {
BBus objB;
return objB; // Calling a private constructor of class 'BBus'
}
*/ int main(int argc, char **argv)
{
BBus obj; BBus obj3;
// obj3 = obj; // 'operator=' is a private member of 'BBus' // testB(obj); // Calling a private constructor of class 'BBus' // BBus obj2(obj); // Calling a private constructor of class 'BBus' C objC; objC.print(); return ;
}

  • Q49. Which of the following statements are valid regarding the usage of STL algorithms with STL containers?
  • A. STL algorithms provide for operations commonly performed on STL containers.
  • B. STL algorithms are used with STL containers through the use of iterators.
  • C. STL algorithms are used with STL containers to prevent conflicts with other programs.
  • D. STL algorithms provide safe multi-threaded access to STL container elements.
  • E. STL algorithms cannot be used to sort STL container elements.
  • A49. AB ?

  • Q50. Which of the following statements correctly describe C++ exceptions?
  • A, When an exception is thrown, and there is more than one applicable exception handler for the given exception type, control is transferred to the handler nearest to the point of the exception.
  • B. When an exception is caught, it cannot be thrown further.
  • C. A try block can be declared without a catch block.
  • D. When an exception is thrown, all objects dynamically created on the heap are released and their destructors invoked.
  • E. If there are multiple catch blocks, the exceptions they catch may not be from the same inheritance hierarchy.
  • A50. C ?

  • Q51. Which of the following declarations correctly use overloading of the "<<" operator of cout to display the contents of a C++ user-defined class of type Record?
  • C. std::ostream& operator <<(std::ostrearas, Records);
  • A51. C
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; //add declaration here int main()
{
Record myRecord; // other code omitted
cout << myRecord << endl;
}

  • Q52. Which of the following are errors with the use of dynamic memory in the C++ code segment below?
  • A. There is an attempt to access memory allocated on the heap after it has been deleted.
  • B. Allocation with the new operation must to be enclosed in a try/catch block.
  • C. There is an attempt to delete an object which was declared on the stack.
  • D. Since the pointer checking is overwritten, the allocated memory cannot be accessed or freed.
  • E. There is an attempt to delete memory allocated on the heap by using a non-pointer.
  • A52. E
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Account {
public:
void deposit(int);
}; int main(int argc, char **argv)
{
Account *checking = new Account;
checking->deposit(); Account myAccount;
myAccount.deposit(); checking = &myAccount; checking->deposit();
delete checking; Account* saving = new Account; Account & rsav = *saving;
rsav.deposit();
delete rsav; // Cannot delete expression of type 'Account' return ;
}

  • Q53. Which of the following statements about the use of virtual functions in C++ are valid?
  • A. A data member can be declared as virtual.
  • B. A static member function can be declared as virtual.
  • C. A virtual function needs to be declared as virtual only in the base class and optionally in the derived classes.
  • D. An operator can be declared as virtual.
  • E. A friend function can be declared as virtual.
  • A53. C ?

  • Q54. Which of the following statements correctly describe the usage of an unrestricted union in C++?
  • A. It is allowed to contain members of class type.
  • B. It is not allowed to contain members of built-in type.
  • C. It has the unrestricted keyword qualifying the union name.
  • D. It must define a constructor.
  • E. It must define an assignment operator.
  • A54. A ?

  • Q55. Which of the following lines of C++ code are valid implementations of the Penguin swim() method defined below?
  • A. SwimmingAnimal.move();
  • B. SwimmingAnimal::move();
  • C. Animal::changePosition(2);
  • D. move();
  • E. position += 2;
  • A55. BC
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Animal {
private:
int position;
public:
Animal() { position = ; }
void changePosition(int i) {
position += i;
}
}; class WalkingAnimal : virtual public Animal {
public:
void move() { changePosition(); }
}; class SwimmingAnimal : virtual public Animal {
public:
void move() { changePosition(); }
}; class Pengiun : public WalkingAnimal, public SwimmingAnimal {
public:
void swim() {
// insert code here
// SwimmingAnimal.move(); // Use of undeclared identifier 'SwimmingAnimal'
SwimmingAnimal::move();
Animal::changePosition();
// move(); // Member 'move' found in multiple base classes of different types
// position += 2; // 'position' is a private member of 'Animal'
}
void walk() {}
}; int main(int argc, char **argv)
{
return ;
}

  • Q56. When overloading C++ unary operators, which of the following are legal options with respect to the number of parameters to be used?
  • A. One (dummy) parameter, when the operator is a particular type of increment/decrement class member function.
  • B. One parameter, when the operator function is a free standing function (not a class member).
  • C. Any number of parameters, when the operator function is a free standing function (not a class member).
  • D. No parameters, when the operator function is a free standing function (not a class member).
  • E. No parameters, when the operator function is a class member.
  • A56. E ?

  • Q57. Which of the following are true statements about the use of std::promise and std::future in the snippet below, when using the multi-threading library that is part of the C++ standard library?
  • A. The return statement on Line C does not return a value to function get() (on Line I) in main(). Other mechanisms are needed to pass return values back to a parent thread.
  • B. After assigning a value to y1 on Line I, the thread function func1() can, in theory, assign a new value to the promise object and that value can be assigned to variable y1 with another call to get() as on Line K.
  • C. If the thread function func1() is still running when the parent thread calls member function get() (at Line I) the function get() will throw an exception.
  • D. If the function on Line B throws an exception, the exception will be reported back to main() similarly to if the function get() (on Line I) threw the exception.
  • E. The get() member functions called on Line M and Line N will block until the thread function func2() has completed and exited.
  • A57. B ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <future>
using namespace std; int func1(std::future<int>& delayedParam)
{
int x = delayedParam.get(); // Line A // do other work here... int y = function_potentially_throwing_exception(); // Line B return y; // Line C
} void func2(std::promise<int> &result, std::promise<bool> &done)
{
// do other work here... result.set_value(); // Line D
done.set_value(true); // Line E // could do other work here...
} int main()
{
//-----------------for func1----------------------------
std::promise<int> promisedArgument;
std::future<int> futureArgument = promisedArgument.get_future(); auto f = std::async(std::launch::async, func1,
std::ref(futureArgument)); // Line F promisedArgument.set_value(); // Line G try {
bool isValid = f.valid(); // Line H
int yl = f.get(); // Line I isValid = f.valid(); // Line J
int y2 = f.get(); // Line K
}
catch (...) {
//...
} //--------------for func2--------------
std::promise<int> resultPromise;
std::promise<bool> donePromise; std::future<int> resultFuture = resultPromise.get_future();
std::future<bool> doneFuture = donePromise.get_future(); std::async(std::launch::async, func2,
std::ref(resultPromise), std::ref(donePromise) ); // Line L bool done = doneFuture.get(); // Line M
int result_f2 = resultFuture.get(); // Line N // do other things with result_f2 ... return ;
}

  • Q58. Which of the following correctly identify the output of executing the C++ code below?
  • D. Type of new_arg is not const / Type of new一arg is not const / Type of new_arg is not const
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; template<class T>
void stripConst( T arg ) {
typename std::remove_const<T>::type new_arg; if (std::is_const< decltype(new_arg) >::value)
cout << "Type of new_arg is const" << endl;
else
cout << "Type of new_arg is not const" << endl;
} int main(int argc, char **argv)
{
stripConst( "Blinkin" );
stripConst( );
stripConst( 3.14 ); return ;
}

  • Q59. For the C++ declarations below which are valid operations?
  • D. team1 = bonds;
  • A59. D
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; enum REG {stocks, bonds};
enum LTC {swaps, swaptions};
enum DRV {futures, options}; REG team1;
LTC team2;
DRV team3; int main(int argc, char **argv)
{
// team2 = 1;
// team1 = stocks + 1;
// team3 = options + futures; team1 = bonds; // team1 = futures; return ;
}

  • Q60. A programmer has decided to store objects of a user-defined type (a structure) in an unordered_set. Which of the following are steps that must be taken in order for this to work properly?
  • A. The structure will have to overload operator() so that elements may be located in the collection.
  • B. The structure will have to create a specialization of std::hash for the user defined type.
  • C. The structure will have to overload operator==() in order for this type to be supported by this collection.
  • D. The structure will have to define a default constructor.
  • E. The structure will have to overload operator<() so that the elements can be stored in the proper place within the collection.
  • A60. C

  • Q61. Given the code below, when using the regular expression library that is part of the C++ standard library, which of the following statements are true after the execution of Line 1?
  • A. The element matches [n] corresponds to the nth character of the match.
  • B. The size() member function of the matches object contains the number of matches found in the target string.
  • C. The element matches [n] corresponds to the nth match of the expression in the target string.
  • D. The size() member function of the matches object contains the number of characters contained in the match.
  • E. The empty() member function of the matches object deletes all of the stored matches.
  • A61. BC ?
  • regex_search - C++ Reference
    • http://www.cplusplus.com/reference/regex/regex_search/?kw=regex_search
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
// #include <iostream>
#include <string>
#include <regex>
using namespace std; int main(int argc, char **argv)
{
smatch matches; string target("this subject has a submarine as a subsequence");
regex expr("\\b(sub)([^ ]*)"); auto x = regex_search(target, matches, expr); // Line 1 return ;
}

  • Q62. A requirements spedficatlon for a C++ class called Rotator calls for the exclusive management of a critical resource. It has been decided to enforce the exclusiveness, in part, by preventing the class from being copied. In addition, the design calls for the use of the compiler generated default constructor for this class. Which of the following are steps that may be taken to implement this part of the requirements?
  • A. Let the compiler generate the default constructor and manually declare that it is final such as Rotator() final; .
  • B. Declare a copy assignment operator, then explicitly delete it such as void operator=(Rotator const &) = delete;.
  • C. Declare a copy constructor, then explicitly delete it such as Rotator (Rotator const &) = delete;.
  • D. Declare the compiler generated constructor to be explicitly defaulted such as Rotator() = default;.
  • E. Let the compiler generate the default constructor and don't make any other reference to it In the class declaration.
  • A62. BC ?

  • Q63. Given the C++ excerpt below, which of the following techniques can be used to assign pointer cw* to pointer w*?
  • A. First assign cw to a temporary variable, then assign the temporary variable to w.
  • B. Make the assignment in the normal way.
  • C. Make the assignment in the normal way with the addition of the reinterpret cast operator.
  • D. Make the assignment in the normal way with the addition of the static_cast operator.
  • E. Make the assignment in the normal way with the addition of the const cast operator.
  • A63. E ?
  • reinterpret_cast 运算符 | Microsoft Docs
    • https://docs.microsoft.com/zh-cn/cpp/cpp/reinterpret-cast-operator
  • static_cast 运算符 | Microsoft Docs
    • https://docs.microsoft.com/zh-cn/cpp/cpp/static-cast-operator
  • const_cast 运算符 | Microsoft Docs
    • https://docs.microsoft.com/zh-cn/cpp/cpp/const-cast-operator
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
// #include <iostream>
using namespace std; class widget {}; int main(int argc, char **argv)
{
widget const *cw = new widget;
widget *w; /*
w = cw; // Assigning to 'widget *' from incompatible type 'const widget *'
w = reinterpret_cast< widget* >(cw); // Reinterpret_cast from 'const widget *' to 'widget *' casts away qualifiers
w = static_cast< widget* >(cw); // Static_cast from 'const widget *' to 'widget *', which are not related by inheritance, is not allowed
*/
w = const_cast< widget* >(cw); return ;
}

  • Q64. Which of the following are correct declarations of a pointer and assignment to the C++ member function avg of class Myciass?
  • A. double (MyClass::ptr)(); ptr = &MyClass::avg;
  • B. double (MyClass::*f)(); f = SMyClass::avg;
  • C. double (*fptr)(); fptr = &MyClass::avg;
  • D. double (MyClass::*f()); *f = SMyClass::avg;
  • E. double (MyClass::*f)() = SMyClass::avg;
  • A64. BE
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class MyClass {
double scores[];
public:
double avg () { return ; }
double high() { return ; }
double low () { return ; }
}; int main(int argc, char **argv)
{
/*
double (MyClass::*f)();
f = &MyClass::avg;
*/ double (MyClass::*f)() = &MyClass::avg; return ;
}

  • Q65. Which of the following statements regarding the C++ program are correct?
  • A. There will a memory leak because the object created on Line A still exists but there is no reference to it and cannot be deleted.
  • B. After the function process () has executed, Line X will retrieve the name "New Fluffy" for the object stray.
  • C. There will be an error on Line B as the pointer myPet no longer refers to any object.
  • D. The move operation on Line D is unnecessary.
  • E. There will be an error on Line X because the object referred to no longer exists.
  • A65. C ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class animal {
string name = "";
public:
void setName(string n) { name = n; }
string getName(void) { return name; }
}; void process(animal *pet)
{
//I already have a pet
unique_ptr<animal> myPet(new animal); // Line A
myPet->setName("Fluffy"); // now you are getting a pet
unique_ptr<animal> yourPet; // I'll give you my pet
yourPet = move(myPet); // Line D // but you can't my pet's name
myPet->setName ("Not Fluffy"); // Line B // I'll take the stray
myPet.reset (pet); // the stray gets a new name
myPet->setName("New Fluffy");
} int main ()
{
// in main... animal *stray = new animal; stray->setName("Scratchy");
process (stray);
string name = stray->getName(); // Line X // other code here return ;
}

  • Q66. In the given C++ code snippet, which of the following statements correctly identify how Mon of enum day can be assigned to a variable named var?
  • A. enum DAY var = Mon;
  • B. DAY var = DAY::Mon;
  • C. enum DAY var = dynamic_cast<enum DAY>(Mon);
  • D. enum DAY var = DAY::Mon;
  • E. enum DAY var = DAY.Mon;
  • A66. ABD
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; int main ()
{
enum DAY { Mon = , Tue = }; enum DAY var = Mon;
DAY var = DAY::Mon;
// enum DAY var = dynamic_cast<enum DAY>(Mon); // 'enum DAY' is not a reference or pointer
enum DAY var = DAY::Mon;
// enum DAY var = DAY.Mon; // 'DAY' does not refer to a value return ;
}

  • Q67. Which of the following are accurate statements concerning the behavior of the dynamic_cast operatorin C++?
  • A. The dynamic_cast operator can only be applied to a pointer or reference to a polymorphic object,
  • B. A dynamic_cast applied to a pointer returns 0 (zero) if the operation fails,
  • C. The dynamic_cast operator’s behavior is a subset of the reinterpret_cast operator's behavior.
  • D. A dynamic_cast applied to a reference throws an exception if the operation fails.
  • E. The dynamic_cast operator fails if used for upcasting.
  • A67. B ?

  • Q68. A programmer has partially defined the C++11 compliant template function below: Not knowing what the lhs and rhs types will be, the coder is not sure how to specify the return value of this function. Which of the following approaches can the programmer take?
  • A. The coder must use auto as the return type and let the compiler determine what to replace it with, such as: auto myfunc (const T1 &lhs, const T2 &rhs) {return lhs + rhs;}
  • B. The coder must use the utility function decltype() to determine the return type, such as: decltype (lhs + rhs) myfunc (const T1 &lhs, const T2 &rhs) {return lhs + rhs;}
  • C. The coder must specify a single return type that will be returned from any instantiation of the template function.
  • D. The coder must use a combination of auto and decltype: auto myfunc (const T1 &lhs, const T2 &rhs) -> decltype (lhs+rhs) {return lhs + rhs;}
  • E. The coder must specify one of template parameter types as the return type, then ensure that the template function converts/casts its results to match that return type.
  • A68. D ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; template<class T1, class T2>
// RETURN-TYPE-HERE myfunc(const T1 &lhs, const T2 &rhs) {return lhs + rhs;}
// auto myfunc (const T1 &lhs, const T2 &rhs) {return lhs + rhs;} // 'auto' return without trailing return type; deduced return types are a C++14 extension // decltype(lhs + rhs) myfunc (const T1 &lhs, const T2 &rhs) {return lhs + rhs;} // Use of undeclared identifier 'rhs' auto myfunc(const T1 &lhs, const T2 &rhs)->decltype(lhs+rhs) {return lhs + rhs;} int main ()
{
return ;
}

  • Q69. Which of the following are NOT valid segments of code when inserted at and in the C++ program segment below (the choices for a given insertion point are not mutually exclusive)?
  • A. **1** : std::unordered_map<std::string, int> colorCommands = {{"red", 3}, {"yellow", 2}, {"green", 1}};
  • B. **1** : std::unordered_map<std::string, int> colorCommands; colorCommands["red”] = 3; colorCommands["yellow"] = 2; colorCommands["green"] = 1;
  • C. **1** : std::unordered_map<std::string, int> colorCommands; colorCommands.insert(std::make_pair("red", 3)); colorCommands.insert({ "yellow", 2 }); colorCommands.emplace("green", 1);
  • D. **2** : switch(colorCommands.find(color))
  • E. **2** : switch (colorCommands[color])
  • A69. D
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <unordered_map> std::string checkTheLight() {
return "green";
} int main ()
{
enum colors {green, yellow, red}; /**1**/
std::unordered_map<std::string, int> colorCommands = {{"red", }, {"yellow", }, {"green", }};
/*
std::unordered_map<std::string, int> colorCommands;
colorCommands["red"] = 3;
colorCommands["yellow"] = 2;
colorCommands["green"] = 1; std::unordered_map<std::string, int> colorCommands;
colorCommands.insert(std::make_pair("red", 3));
colorCommands.insert({ "yellow", 2 });
colorCommands.emplace("green", 1);
*/
std::string color = checkTheLight(); /**2**/
// switch (colorCommands.find(color)) // Statement requires expression of integer type ('iterator' (aka '__hash_map_iterator<__hash_iterator<std::__1::__hash_node<std::__1::__hash_value_type<std::__1::basic_string<char>, int>, void *> *> >') invalid) switch (colorCommands[color])
{
case green:
std::cout << "get going";
break;
case yellow:
std::cout << "slow down";
break;
case red:
default:
std::cout << "stop";
break;
} std::cout << std::endl; return ;
}

  • Q70. A programmer wishes to construct a new type trait, based on is_floating_point<T> In the C++11 standard library. This new trait will validate not only the built-in floating point types, but std::complex<T>, parameterized by those same types, as well. Which of the following declarations will accomplish this?
  • A. template< class T > struct is_complex_or_fp< std::complex< T > > std::is_floating_point< T > { };
  • B. template< class T > struct is_complex_or_fp : std::is_floating_point< T > { static constexpr bool value{true}; };
  • C. template< class T > struct is_complex_or_fp : std::ia_floating_point< T > { }; template< class T > struct is_complex_or_fp< T > : std::is_floating_point< std::complex< T > > { };
  • D. template< class T > struct is_complex_or_fp : std::is_floating_point< T > { };template< class T > struct is_complex_or_fp< std::complex< T > > : std::is_floating_point< T > { };
  • E. template< class T > struct is_complex_or_fp< T > : std::is_floating_point< std::complex< T > > { };
  • A70. BD
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
#include <complex> /*
template< class T >
struct is_complex_or_fp< std::complex< T > > std::is_floating_point< T > { }; // Explicit specialization of non-template struct 'is_complex_or_fp'
*/ template< class T >
struct is_complex_or_fp : std::is_floating_point< T > { static constexpr bool value{true}; }; /*
template< class T >
struct is_complex_or_fp : std::is_floating_point< T > { }; template< class T >
struct is_complex_or_fp< T > : std::is_floating_point< std::complex< T > > { }; // Class template partial specialization does not specialize any template argument; to define the primary template, remove the template argument list
*/ template< class T >
struct is_complex_or_fp : std::is_floating_point< T > { }; template< class T >
struct is_complex_or_fp< std::complex< T > > : std::is_floating_point< T > { }; /*
template< class T >
struct is_complex_or_fp< T > : std::is_floating_point< std::complex< T > > { }; // Explicit specialization of non-template struct 'is_complex_or_fp'
*/ int main ()
{
return ;
}

  • Q71. Which of the following statements are true with respect to the C++ code excerpt below?
  • A. The constructor Course (double d) may not call another constructor such as Course (int a).
  • B. The default constructor results in an object with all data members uninitialized.
  • C. The default constructor results in an object with all data members initialized with the values shown in the class definition.
  • D. The use of braces for the class instantiation of objects course1, course2, course3 and course4 is not valid C++ syntax.
  • E. Static data members may not be initialized in the class definition as shown.
  • A71. E ?
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream> class Course {
static int classCount = ; // Non-const static data member must be initialized out of line
std::string courseName {"CS101"};
int room = ;
int quizzes[] {, , , , }; public:
Course( ) {};
Course(int a) : room(a) {}
Course (std::string b) : courseName(b), room() {}
Course(double d) : Course( static_cast<int>(d) ) {}
}; int main ()
{
Course course1{};
Course course2{};
Course course3{"EnglishlOl"};
Course course4{3.14}; return ;
}

  • Q72. Which of the following changes must be made to the C++ code below so that the widget class definition is const-correct for its usage in main() ?
  • A. Change Widget(Widget& w); to Widget(const Widget& w);
  • B. Change Gizmo (int p, int r) ; to Gizmo (const int p, const int r);
  • C. Change Widget& operator=(Widget& rhs); to Widget& operator=(const Widget& rhs);
  • D. Change Widget (Gizmo& g) ; to Widget (const Gizmo& g);
  • E. Use const_cast during assignment otherWidget = basicWidget;
  • A72. AD
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream> struct Gizmo {
int pressure, rpm;
Gizmo(int p, int r) : pressure(p), rpm(r) {}
// Gizmo(const int p, const int r) : pressure(p), rpm(r) {}
}; struct Widget {
int temp, speed;
Widget() : temp (), speed() {} // Widget(Widget& w);
Widget(const Widget& w); Widget& operator=(Widget& rhs);
// Widget& operator=(const Widget& rhs); // Widget(Gizmo& g);
Widget(const Gizmo& g);
}; int main(int argc, char **argv)
{
const Widget prototype; Widget basicWidget = prototype; // No matching constructor for initialization of 'Widget' Widget otherWidget;
otherWidget = basicWidget; const Gizmo gadget(, ); Widget thirdWidget(gadget); // No matching constructor for initialization of 'Widget' return ;
}

  • Q73. Which of following actions are required to achieve the specifications of the C++ class which will contain some special purpose "helper" functionality with the requirements specified below?

    • 1) The functionality is used by more than one public member function in a given class.
    • 2) The functionality accesses private data members of the class.
    • 3) The functionality must be a separate function.
    • 4) The functionality must be available to derived classes but not available to users of the derived directly.
  • A. Put the functionality in a member function and make its access level private.
  • B. Put the functionality in a friend function of the given class.
  • C. Put the functionality in a member function and make its access level protected.
  • D. Put the functionality in a separate class and inherit from that class.
  • E. Put the functionality in a global function that is called by the class.
  • A73. B ?

  • Q74. In the C++ class Box below, the == operator is overloaded such that boxes of the same volume are considered "equal". Given the two boxes of this type(called box1 and box2) comparisons 1 and 2 may be made. Which can be used to implement the 3rd (comparison 3) shown below?
  • A. Implement a member operator== taking a Box and a double.
  • B. Implement a global function called operator== which takes a double and a Box and makes it a friend of class Box.
  • C. Modify one of the existing member operator== implementations so that it takes an additional parameter.
  • D. The existing overloaded operators already handle the 3rd comparison.
  • E. Implement a global functino called operator== which takes a double and a Box and have it call an existing member operator== implementation with conforming parameters.
  • A74. B
 //
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
//
// main.cpp
// LeetCode
//
// Created by Hao on 2017/3/16.
// Copyright © 2017年 Hao. All rights reserved.
//
#include <iostream>
using namespace std; class Box {
double volume;
public:
Box() {};
Box(double v) : volume(v) {}; bool operator==(Box &rhs) {
return this->volume == rhs.volume;
} bool operator==(double v) {
Box rhs(v);
return volume == rhs.volume;
}
/*
bool operator==(Box &rhs, double v) { // Overloaded 'operator==' must be a binary operator (has 3 parameters)
Box temp(v);
return rhs.volume == temp.volume;
}
*/
friend bool cmp(double v, Box &rhs); // must declared w/ the parameter nameb98
}; bool cmp(double v, Box &rhs) {
Box temp(v);
return rhs.volume == temp.volume;
} int main(int argc, char **argv)
{
Box box1, box2(8.75); if (box1 == 7.25) // comparison 1
cout << << endl; if (box1 == box2) // comparison 2
cout << << endl; /*
// Invalid operands to binary expression ('double' and 'Box')
if (8.75 == box2) // comparison 3
cout << 3 << endl;;
*/ if (cmp(8.75, box2))
cout << << endl; return ;
}

  • Q75. What's the situation used for std::unexpected()?
  • A75. ?

学习笔记之IKM C++ 11的更多相关文章

  1. PHP学习笔记 - 进阶篇(11)

    PHP学习笔记 - 进阶篇(11) 数据库操作 PHP支持哪些数据库 PHP通过安装相应的扩展来实现数据库操作,现代应用程序的设计离不开数据库的应用,当前主流的数据库有MsSQL,MySQL,Syba ...

  2. Web 在线文件管理器学习笔记与总结(11)获取文件夹信息 (12)返回上一级操作

    (11)获取文件夹信息 文件夹没有修改操作. index.php: <?php require 'dir.func.php'; require 'file.func.php'; require ...

  3. 我的学习笔记_Windows_HOOK编程 2009-12-03 11:19

    一.什么是HOOK? "hook"这个单词的意思是"钩子","Windows Hook"是Windows消息处理机制的一个重要扩展,程序猿能 ...

  4. 我的学习笔记_Windows_HOOK计划 2009-12-03 11:19

    一.什么是HOOK? "hook"这个单词的意思是"钩子","Windows Hook"是Windows消息处理机制的一个重要扩展,程序猿能 ...

  5. 再起航,我的学习笔记之JavaScript设计模式11(外观模式)

    经过一段时间的学习与分享,我们对创建型设计模式已经有了一定的认识,未来的一段时间里我们将展开新的篇章,开始迈入结构性设计模式的学习. 结构性设计模式与创建型设计模式不同,结构性设计模式更偏向于关注如何 ...

  6. C++学习笔记16,C++11中的显式的默认构造函数以及显示删除默认构造函数

    在早期的C++中.假设须要一些接受一些參数的构造函数,同一时候须要一个不接收不论什么參数的默认构造函数.就必须显示地编写空的默认构造函数.比如: //tc.h class A{ private: in ...

  7. java学习笔记—Servlet技术(11)

    如果大家要开发一个动态的网站,那么就必须要学习一种动态的网页开发技术.那么在SUN提供的JavaEE中主要包含两种开发动态网页的技术:Servlet和JSP技术. Servlet技术简介 Servle ...

  8. 【Python学习笔记】macosx 10.11 python pip install 出现错误OSError: [Errno 1] Operation not permitted:

    http://www.cnblogs.com/xiongqiangcs/p/4914049.html pip install --upgrade pip sudo pip install numpy ...

  9. 前端学习笔记系列一:11@vue/cli3.x中实现跨域的问题

    由于浏览器的同源访问策略,vue开发时前端服务器通常与后端api服务器并非是相同的服务器,因此需要使用一个代理服务器实现跨域访问.在@vue/cli3.x根目录下创建一个vue.config.js文件 ...

随机推荐

  1. ZooKeeper 之 zkCli.sh客户端的命令使用

    zkCli.sh的使用 ZooKeeper服务器简历客户端 ./zkCli.sh -timeout 0 -r -server ip:port ./zkCli.sh -timeout 5000 -ser ...

  2. PostgreSQL11.2 configure卡住 checking for DocBook XML V4.2

    在PG11.2的数据库编译过程中,卡在了“checking for DocBook XML V4.2”,不动,需要安装docbook才可以. 需要安装: yum install docbook-dtd ...

  3. encodeURI、encodeURIComponent、decodeURI、decodeURIComponent的区别

    一.这四个方法的用处 1.用来编码和解码URI的 统一资源标识符,或叫做 URI,是用来标识互联网上的资源(例如,网页或文件)和怎样访问这些资源的传输协议(例如,HTTP 或 FTP)的字符串.除了e ...

  4. Ubuntu install TensorFlow

    /******************************************************************************** * Ubuntu install T ...

  5. OpenCV Error: Insufficient memory问题解析

    前言 项目程序运行两个月之久之后突然挂了,出现OpenCV Error: Insufficient memory的错误,在此分析一下该问题. 问题的表现形式: 程序内存使用情况: 问题: OpenCV ...

  6. c++ 字符数组-print and 写入文件

    1.print ][] = { }; method1: 为了打印出unsigned char数据所对应的数值,可以将其强制转换成int类型,并做打印输出. std::cout << ][] ...

  7. 20155338 2016-2017-2 《Java程序设计》第8周学习总结

    20155338 2016-2017-2 <Java程序设计>第8周学习总结 教材学习内容总结 一.日志 API简介 java++.util.logging包提供了日志功能相关类与接口,不 ...

  8. HDU1702:ACboy needs your help again!

    ACboy needs your help again! Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ( ...

  9. python笔记-6(import导入、time/datetime/random/os/sys模块)

    一.了解模块导入的基本知识 此部分此处不展开细说import导入,仅写几个点目前的认知即可.其它内容待日后有深入理解了再来细说 1.import可以导入的两种不同的内容 1.1 *.py文件结尾的文件 ...

  10. day25 python学习 继承,钻石继承

    通过一个列子认识父类和子类中,子类的如何实现对父类默认属性调用,同时拥有自己的属性,如何在子类中调用父类的方法,class Ainmal: country='afdas' def __init__(s ...