声明一个book类:
#include<iostream>
using namespace std;
class Book
{
public:
string name;
string author;
int pages;
};
int main()
{
Book book1;
book1.name = "Lord of Rings";
book1.author = "Tolkien";
book1.pages = 490;
Book book2;
book2.name = "The Chronicles of Narnia";
book2.author = "Lewis";
book2.pages = 520;
cout << "book1: " << endl << book1.name << endl
<< book1.author << endl << book1.pages << " pages" << endl;
cout << "book2: " << endl << book2.name << endl
<< book2.author << endl << book2.pages << " pages" << endl;
return 0;
}
类成员函数:
#include<iostream>
using namespace std;
class Book
{
private:
float price;
public:
string name;
string author;
int pages;
Book() // same as class name
{
name = "no name";
author = "no author";
pages = 0;
price = 0.;
} // no need of semicolon here
Book(string aName, string aAuthor, int aPages, float aPrice){
name = aName;
author = aAuthor;
pages = aPages;
price = aPrice;
}
string bigbook(){
if (pages > 500){
return "T";
}
return "F";
};
float showprice(){
return price;
}
void setprice(float aPrice){
if (aPrice >= 0 ){
price = aPrice;
}
}
};
int main()
{
Book book1("Lord of Rings","Tolkien",490,9.4);
Book book2; // no parentheses here
cout << "book1: " << endl << book1.name << endl
<< book1.author << endl << book1.pages << " pages" << endl;
cout << book1.showprice() << endl;
book1.setprice(99.9);
cout << book1.showprice() << endl;
cout << "book2: " << endl << book2.name << endl
<< book2.author << endl << book2.pages << " pages" << endl;
cout << book2.showprice() << endl;
cout << book1.bigbook() << endl;
return 0;
}
类继承:
#include<iostream>
using namespace std;
class Book
{
private:
float price;
public:
string name;
string author;
int pages;
Book() // same as class name
{
name = "no name";
author = "no author";
pages = 0;
price = 0.;
} // no need of semicolon here
Book(string aName, string aAuthor, int aPages, float aPrice){
name = aName;
author = aAuthor;
pages = aPages;
price = aPrice;
}
string bigbook(){
if (pages > 500){
return "T";
}
return "F";
};
float showprice(){
return price;
}
void setprice(float aPrice){
if (aPrice >= 0 ){
price = aPrice;
}
}
};
class Ebook : public Book{
public :
string format;
Ebook(string aName, string aAuthor, int aPages, string aFormat){
name = aName;
author = aAuthor;
pages = aPages;
format = aFormat;
}
};
int main()
{
Book book1("Lord of Rings","Tolkien",490,9.4);
Book book2; // no parentheses here
Ebook book3("c++ Primer Plus", "Prata",680,"txt");
cout << "book1: " << endl << book1.name << endl
<< book1.author << endl << book1.pages << " pages" << endl;
cout << book1.showprice() << endl;
book1.setprice(99.9);
cout << book1.showprice() << endl;
cout << "book2: " << endl << book2.name << endl
<< book2.author << endl << book2.pages << " pages" << endl;
cout << book2.showprice() << endl;
cout << book1.bigbook() << endl;
book3.setprice(33.4);
cout << book3.name << book3.format << endl;
cout << book3.showprice() << endl;
return 0;
}