cpp / beginner
Snippet
Building a Simple Class
A class is a blueprint for creating objects that bundle data and functions together. This Dog class has two member variables (name and age) and one member function (bark). The public keyword means these members are accessible from outside the class. To use a class, you create an instance (myDog) which allocates memory for that object. You access members using the dot operator (.) to set values or call methods.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>#include <string>class Dog {public:std::string name;int age;void bark() {std::cout << name << " says: Woof!" << std::endl;}};int main() {Dog myDog;myDog.name = "Buddy";myDog.age = 3;myDog.bark();return 0;}
Breakdown
1
class Dog {
Class definition开始 for blueprint named Dog
2
public:
Access specifier making members accessible outside class
3
std::string name;
Member variable to store the dog's name
4
int age;
Member variable to store the dog's age
5
void bark() {
Member function that prints a bark message
6
Dog myDog;
Creates an instance of the Dog class
7
myDog.name = "Buddy";
Uses dot operator to access and set member variable
8
myDog.bark();
Calls the member function using dot operator