class Person {
public:
Person(); // parameters omitted for simplicity
virtual ~Person(); // see Item 7 for why this is virtual
...
PRivate:
std::string name;
std::string address;
};
class Student: public Person {
public:
Student(); // parameters again omitted
~Student();
...
private:
std::string schoolName;
std::string schoolAddress;
};
bool validateStudent(Student s); // function taking a Student
// by value
Student plato; // Plato studied under Socrates
bool platoIsOK = validateStudent(plato); // call the function
bool validateStudent(const Student& s);
class Window {
public:
...
std::string name() const; // return name of window
virtual void display() const; // draw window and contents
};
class WindowWithScrollBars: public Window {
public:
...
virtual void display() const;
};
void printNameAndDisplay(Window w) // incorrect! parameter
{
// may be sliced!
std::cout << w.name();
w.display();
}
WindowWithScrollBars wwsb;
printNameAndDisplay(wwsb);
void printNameAndDisplay(const Window& w) // fine, parameter won’t
{
// be sliced
std::cout << w.name();
w.display();
}
新闻热点
疑难解答