C++单继承,对象引用做函数参数举例
时间: 2023-08-12 21:24:33 浏览: 41
好的,假设我们有一个基类Animal,和两个派生类Cat和Dog。我们可以定义一个函数feed,接受一个Animal对象的引用作为参数:
```c++
class Animal {
public:
virtual void makeSound() = 0;
};
class Cat : public Animal {
public:
void makeSound() override {
cout << "Meow" << endl;
}
};
class Dog : public Animal {
public:
void makeSound() override {
cout << "Woof" << endl;
}
};
void feed(Animal& animal) {
cout << "Feeding animal..." << endl;
animal.makeSound();
}
```
接下来我们可以创建一个Cat对象和一个Dog对象,然后将它们分别传递给feed函数进行喂养:
```c++
int main() {
Cat cat;
Dog dog;
feed(cat);
feed(dog);
return 0;
}
```
这样,程序会依次输出:
```
Feeding animal...
Meow
Feeding animal...
Woof
```
相关问题
c++ 继承 举例说明
当一个类从另一个类派生出来时,我们称之为继承。在 C++ 中,我们使用关键字 "class" 来定义一个类,使用关键字 "public" 来指定继承方式。下面是一个简单的继承示例:
```
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};
int main() {
Dog myDog;
myDog.eat(); // 继承自 Animal 类
myDog.bark();
return 0;
}
```
在上面的示例中,我们定义了一个 Animal 类,它有一个 eat() 方法。然后我们定义了一个 Dog 类,它继承自 Animal 类,并添加了一个 bark() 方法。在 main() 函数中,我们创建了一个 Dog 对象,并调用了它的 eat() 和 bark() 方法。由于 Dog 类继承自 Animal 类,因此它可以使用 Animal 类中定义的 eat() 方法。
请举例解释c++继承
好的,假设有一个基类Animal,它有三个成员变量和两个成员函数:
```c++
class Animal {
private:
int age;
string name;
string species;
public:
void eat() {
cout << "Animal is eating." << endl;
}
void sleep() {
cout << "Animal is sleeping." << endl;
}
};
```
现在我们要创建一个派生类Dog,它继承了基类Animal的所有成员变量和成员函数,并且还有自己的一些成员变量和成员函数:
```c++
class Dog : public Animal {
private:
string breed;
public:
void bark() {
cout << "Dog is barking." << endl;
}
};
```
这个例子中,我们使用public关键字将Dog类声明为公有继承Animal类的派生类。这意味着Dog类可以访问Animal类的公有成员函数和变量。
现在我们可以创建一个Dog对象,并调用它继承的成员函数和自己的成员函数:
```c++
int main() {
Dog mydog;
mydog.eat(); // 调用继承自Animal类的eat()函数
mydog.bark(); // 调用Dog类自己的bark()函数
return 0;
}
```
这个程序将输出:
```
Animal is eating.
Dog is barking.
```
这说明Dog类成功地继承了Animal类的成员函数,并添加了自己的成员函数。