1.类样例
#include <iostream>
using namespace std;
#define endline "\n"
#include <cstring>
#include <string>
class Dog
{
private:
string name;
int age;
public:
void run();
void eat(char *obj)
{
cout << "the dog is eating " << obj << endline;
}
void setname(string _name)
{
name = _name;
}
string getname();
void setage(int _age)
{
age = _age;
}
int getage();
};
void Dog::run()
{
printf("the dog is running...\n");
}
string Dog::getname()
{
return name;
}
int Dog::getage()
{
return age;
}
int main()
{
Dog dog;
char food[] = "shit";
dog.eat(food);
dog.run();
string _name = "erha";
dog.setname(_name);
int _age = 20;
dog.setage(_age);
string name = dog.getname();
int age = dog.getage();
cout << "the dog's name is " << name << endline;
cout << "the dog's age is " << age << endline;
cout << _name[1] << endline;
return 0;
}
2.继承
#include <iostream>
using namespace std;
#include <string>
class Shape
{
public:
int width;
int height;
void setwidth(int w)
{
width = w;
}
void setheight(int h)
{
height = h;
}
};
class Square: public Shapea
{
public:
int getarea()
{
return width*height;
}
};
int main()
{
Square square;
int w = 20;
int h = 30;
square.setwidth(w);
square.setheight(h);
int area = square.getarea();
cout << "the square is " << area << "\n";
return 0;
}
3.重载函数
#include <iostream>
using namespace std;
#include <string>
class Output
{
public:
void print(int i)
{
cout << i << "\n";
}
void print(string s)
{
cout << s << "\n";
}
};
int main()
{
Output output;
int i = 10;
string s = "hello";
output.print(i);
output.print(s);
}
4.重载运算符
#include <iostream>
using namespace std;
#include <string>
class Box
{
public:
int width;
int height;
Box(int w,int h)
{
width = w;
height = h;
}
Box operator+(const Box& b)
{
Box box(0,0);
box.width = this->width + b.width;
box.height = this->height + b.height;
return box;
}
};
int main()
{
Box box1(10,20);
Box box2(30,40);
Box box3 = box1 + box2;
cout << "new box width = " << box3.width << "\n";
cout << "new box height = " << box3.height << "\n";
}
5.虚函数
#include <iostream>
using namespace std;
#include <string>
class Shape
{
public:
virtual int getarea(int length) = 0;
};
class Circle:public Shape
{
public:
int getarea(int length)
{
cout << 3.14 * length * length << "\n";
}
};
class Square:public Shape
{
public:
int getarea(int length)
{
cout << length * length << "\n";
}
};
int main()
{
int length = 10;
Circle circle;
Square square;
circle.getarea(length);
square.getarea(length);
}