21xrx.com
2024-06-03 04:59:52 Monday
登录
文章检索 我的文章 写文章
C++类与对象基础题目
2023-07-09 02:01:05 深夜i     --     --
C++类 C++对象 基础题目

C++是一种功能强大的编程语言,其面向对象编程(OOP)的概念是学习C++的关键。在学习OOP的过程中,理解C++类与对象的基础知识是不可或缺的。以下是一些涉及C++类与对象的基础题目。

1. 创建一个C++类,用于存储学生的姓名和年龄。为该类编写构造函数和析构函数。

class Student {

private:

  std::string name;

  int age;

public:

  Student(std::string name, int age)

    this->name = name;

    this->age = age;

  ~Student() {}

};

2. 创建一个C++类,用于实现一个基本的计算器。该类应该具有用于加、减、乘、除的成员函数。

class Calculator {

public:

  int add(int x, int y) {

    return x + y;

  }

  int subtract(int x, int y)

    return x - y;

  int multiply(int x, int y) {

    return x * y;

  }

  int divide(int x, int y)

    return x / y;

};

3. 创建一个C++类,用于存储一个人的姓名和地址。该类应该包含两个成员变量(姓名和地址),并且具有成员函数,用于设置和获取这些变量的值。

class Person {

private:

  std::string name;

  std::string address;

public:

  void setName(std::string name)

    this->name = name;

  void setAddress(std::string address)

    this->address = address;

  std::string getName()

    return name;

  std::string getAddress()

    return address;

};

4. 创建一个C++类,用于实现一个基本的银行账户。该类应该具有成员函数,用于存款、取款和查询余额。

class BankAccount {

private:

  double balance;

public:

  BankAccount(double balance)

    this->balance = balance;

  void deposit(double amount) {

    balance += amount;

  }

  void withdraw(double amount) {

    if (amount > balance)

      std::cout << "Insufficient funds." << std::endl;

    else

      balance -= amount;

  }

  double getBalance()

    return balance;

};

5. 创建一个C++类,用于存储矩形的长度和宽度。该类应该具有成员函数,用于计算矩形的面积和周长。

class Rectangle {

private:

  double length;

  double width;

public:

  Rectangle(double length, double width)

    this->length = length;

    this->width = width;

  double getArea() {

    return length * width;

  }

  double getPerimeter() {

    return 2 * (length + width);

  }

};

在学习OOP的过程中,理解C++类与对象的基础知识是必要的。通过编写这些基础的题目,可以加深对C++类和对象的理解,从而更好地运用OOP的概念来解决实际问题。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复