1. Trang chủ
  2. » Công Nghệ Thông Tin

C++ Primer Plus (P73) potx

20 265 1
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 20
Dung lượng 40,01 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

.2: Suppose the song function has this prototype:void songchar * name, int times; How would you modify the prototype so that the default value for times is 1?. A: This can be done using

Trang 1

.2: Suppose the song() function has this prototype:

void song(char * name, int times);

How would you modify the prototype so that the default value for times

is 1?

a.

What changes would you make in the function definition?

b.

Can you provide a default value of "O, My Papa" for name?

c.

A:

void song(char * name, int times = 1);

a.

None Only prototypes contain the default value information.

b.

Yes, providing you retain the default value for times:

void song(char * name = "O, My Papa", int times = 1);

c.

.3: Write overloaded versions of iquote(), a function that displays its argument enclosed in double quotation marks Write three versions: one for an int argument, one for a double argument, and one for a string argument.

A: You can use either the string "\"" or the character '"' to print a quotation mark.

The following functions show both methods.

#include <iostream.h>

void iquote(int n) {

cout << "\"" << n << "\"";

} void iquote(double x) {

cout << '"' << x << '"';

}

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks

Trang 2

void iquote(const char * str) {

cout << "\"" << str << "\"";

}

.4: Here is a structure template:

A:

This function shouldn't alter the structure members, so use the const qualifier.

void show_box(const box & container) {

cout << "Made by " << container maker << "\n";

cout << "Height = " << container.height << "\n";

cout << "Width = " << container.width << "\n";

cout << "Length = " << container.length << "\n";

cout << "Volume = " << container.volume << "\n";

}

a.

void set_volume(box & crate) {

crate.volume = crate.height * crate.width * crate.length;

}

b.

.5: Here are some desired effects Indicate whether each can be accomplished with default arguments, function overloading, both, or neither Provide appropriate prototypes.

mass(density, volume) returns the mass of an object having a density

of density and a volume of volume, whereas mass(density) returns the mass having a density of density and a volume of 1.0 cubic meters

All quantities are type double.

a.

Trang 3

repeat(10, "I'm OK") displays the indicated string ten times, whereas repeat("But you're kind of stupid") displays the indicated string five times.

b.

average(3,6) returns the int average of two int arguments, whereas average(3.0, 6.0) returns the double average of two double values.

c.

mangle("I'm glad to meet you") returns the character I or a pointer to the string "I'm mad to gleet you" depending on whether you assign the return value to a char variable or to a char* variable.

d.

A:

This can be done using a default value for the second argument:

double mass(double d, double v = 1.0);

It can also be done by overloading:

double mass(double d, double v);

double mass(double d);

a.

You can't use a default for the repeat value because you have to provide default values from right to left You can use overloading:

void repeat(int times, const char * str);

void repeat(const char * str);

b.

You can use function overloading:

int average(int a, int b);

double average(double x, double y);

c.

You can't do this one because both versions would have the same signature.

d.

.6: Write a function template that returns the larger of its two arguments.

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks

Trang 4

template<class T>

T max(T t1, T t2) // or T max(const T & t1, const T & t2) {

return t1 > t2? t1 : t2;

}

.7: Given the template of Review Question 6 and the box structure of Review Question 4, provide a template specialization that takes two box arguments and returns the one with the larger volume.

A:

template<> box max(box b1, box b2) {

return b1.volume > b2.volume? b1 : b2;

}

Chapter 9

.1: What storage scheme would you use for the following situations?

homer is a formal argument (parameter) to a function.

a.

The secret variable is to be shared by two files.

b.

The topsecret variable is to be shared by the functions in one file but hidden from other files.

c.

beencalled keeps track of how many times the function containing it has been called.

d.

A:

homer is automatically an automatic variable.

a.

Trang 5

secret should be defined as an external variable in one file and declared using extern in the second file.

b.

topsecret could be defined as a static variable with internal linkage by prefacing the external definition with the keyword static Or it could be defined in an unnamed namespace.

c.

beencalled should be defined as a local static variable by prefacing a declaration in the function with the keyword static.

d.

.2: Discuss the differences between a using-declaration and a using-directive.

A: A using declaration makes a single name from a namespace available, and it has the scope corresponding to the declarative region in which the using declaration occurs A using directive makes all the names in a namespace available When you use a using directive, it is as if you declared the names in the smallest declarative region containing both the using declaration and the namespace itself.

.3: Rewrite the following so that it doesn't use using-declarations or using-directives.

#include <iostream>

using namespace std;

int main() {

double x;

cout << "Enter value: ";

while (! (cin >> x) ) {

cout << "Bad input Please enter a number: ";

cin.clear();

while (cin.get() != '\n') continue;

} cout << "Value = " << x << endl;

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks

Trang 6

return 0;

}

A:

#include <iostream>

using namespace std;

int main() {

double x;

std::cout << "Enter value: ";

while (! (std::cin >> x) ) {

std::cout << "Bad input Please enter a number: ";

std::cin.clear();

while (std::cin.get() != '\n') continue;

} std::cout << "Value = " << x << std::endl;

return 0;

}

.4: Rewrite the following so that it uses using-declarations instead of the using-directive.

#include <iostream>

using namespace std;

int main() {

double x;

cout << "Enter value: ";

while (! (cin >> x) ) {

cout << "Bad input Please enter a number: ";

cin.clear();

while (cin.get() != '\n')

Trang 7

continue;

} cout << "Value = " << x << endl;

return 0;

}

A: Rewrite the following so that it uses using declarations instead of the using directive.

#include <iostream>

int main() {

using std::cin;

using std::cout;

using std::endl;

double x;

cout << "Enter value: ";

while (! (cin >> x) ) {

cout << "Bad input Please enter a number: ";

cin.clear();

while (cin.get() != '\n') continue;

} cout << "Value = " << x << endl;

return 0;

}

.5: The average(3,6) function returns an int average of the two int arguments when called in one file, and it returns a double average of the two int arguments when called in a second file in the same program How could you set this up?

A: You could have separate static function definitions in each file Or each file could define the appropriate average() function in an unnamed namespace.

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks.

Trang 8

.6: What will the following two-file program display?

// file1.cpp

#include <iostream>

using namespace std;

void other();

void another();

int x = 10;

int y;

int main() {

cout << x << endl;

{ int x = 4;

cout << x << endl;

cout << y << endl;

} other();

another();

return 0;

} void other() {

int y = 1;

cout << "Other: " << x << "," << y << endl;

} // file 2.cpp

#include <iostream>

using namespace std;

extern int x;

namespace {

int y = -4;

} void another()

Trang 9

{ cout << "another(): " << x << ", " << y << endl;

}

A:

10 4 0 Other: 10, 1 another(): 10, -4

.7: What will the following program display?

#include <iostream>

using namespace std;

void other();

namespace n1 {

int x = 1;

} namespace n2 {

int x = 2;

} int main() {

using namespace n1;

cout << x << endl;

{ int x = 4;

cout << x << ", " << n1::x << ", " << n2::x << endl;

} using n2::x;

cout << x << endl;

other();

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks

Trang 10

return 0;

} void other() {

using namespace n2;

cout << x << endl;

{ int x = 4;

cout << x << ", " << n1::x << ", " << n2::x << endl;

} using n2::x;

cout << x << endl;

}

A:

1

4, 1, 2 2 2

4, 1, 2 2

Chapter 10

.1: What is a class?

A: A class is a definition of a user-defined type A class declaration specifies how data is to

be stored, and it specifies the methods (class member functions) that can be used to access and manipulate that data.

.2: How does a class accomplish abstraction, encapsulation, and data hiding?

A: A class represents the operations one can perform on a class object with a public interface of class methods; this is abstraction The class can use private visibility (the

Trang 11

default) for data members, meaning that the data can be accessed only through the member functions; this is data hiding Details of the implementation, such as data representation and method code, are hidden; this is encapsulation.

.3: What is the relationship between an object and a class?

A: The class defines a type, including how it can be used An object is a variable or other data object, such as that produced by new, created and used according to the class definition The relationship is the same as that between a standard type and a variable of that type.

.4: In what way, aside from being functions, are class function members different from class data members?

A: If you create several objects of a given class, each object comes with storage for its own set of data But all the objects use the one set of member functions (Typically, methods are public and data members are private, but that's a matter of policy, not of class requirements.)

Note

The program uses cin.get(char *, int) instead of cin >>

to read names because cin.get() reads a whole line instead of just one word (see Chapter 4 ).

.5: Define a class to represent a bank account Data members should include the depositor's name, the account number (use a string), and the balance Member functions should allow the following:

Creating an object and initializing it.

Displaying the depositor's name, account number, and balance

Depositing an amount of money given by an argument

Withdrawing an amount of money given by an argument

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks

Trang 12

Just show the class declaration, not the method implementations (Programming Exercise

1 provides you with an opportunity to write the implementation.)

A:

#include <iostream>

using namespace std;

// class definition class BankAccount {

private:

char name[40];

char acctnum[25];

double balance;

public:

BankAccount(const char * client = "X", const char * num = "X", double bal = 0;) void show(void) const;

void deposit(double cash);

void withdraw(double cash);

};

.6: When are class constructors called? When are class destructors called?

A: A class constructor is called when you create an object of that class or when you explicitly call the constructor The class destructor is called when the object expires.

.7: Provide code for a constructor for the bank account class of question 5.

A: Note that you must include cstring or string.h in order to use strncpy()

BankAccount::BankAccount(const char * client, const char * num, double bal) {

strccpy(name, client, 39);

name[39] = '\0';

strncpy(acctnum, num, 24);

acctnum[24] = '\0';

Trang 13

balance = bal;

}

Keep in mind that default arguments go in the prototype, not in the function definition.

.8: What is a default constructor and what's the advantage of having one?

A: A default constructor is one with no arguments or else with defaults for all the arguments.

Having one enables you to declare objects without initializing them, even if you've already defined an initializing constructor It also allows you to declare arrays.

.9: Modify the Stock class (the version in stock2.h) so that it has member functions that return the values of the individual data members Note: A member that returns the company name should not provide a weapon for altering the array That is, it can't simply return a char * It could return a const pointer, or it could return a pointer to a copy of the array, manufactured by using new.

A:

// stock3.h

#ifndef STOCK3_H_

#define STOCK3_H_

class Stock {

private:

char company[30];

int shares;

double share_val;

double total_val;

void set_tot() { total_val = shares * share_val; } public:

Stock(); // default constructor Stock(const char * co, int n, double pr);

~Stock() {} // do-nothing destructor void buy(int num, double price);

void sell(int num, double price);

void update(double price);

void show() const;

This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks

Trang 14

const Stock & topval(const Stock & s) const;

int numshares() const { return shares; } double shareval() const { return share_val; } double totalval() const { return total_val; } const char * co_name() const { return company; } };

.10: What are this and *this?

A: The this pointer is a pointer available to class methods It points to the object used to invoke the method Thus, this is the address of the object, and *this represents the object itself.

Chapter 11

.1: Use a member function to overload the multiplication operator for the Stonewt class; have the operator multiply the data members by a type double value

Note that this will require carryover for the stone-pound representation That is, twice 10 stone 8 pounds is 21 stone 2 pounds.

A: Here's a prototype for the class definition file and a function definition for the methods file:

// prototype Stonewt operator*(double mult);

// definition let constructor do the work Stonewt Stonewt::operator*(double mult) {

return Stonewt(mult * pounds);

}

.2: What are the differences between a friend function and a member function?

A: A member function is part of a class definition and is invoked by a particular object The member function can access members of the invoking object

Ngày đăng: 07/07/2014, 06:20

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN