C++——类型转换

一、类型转换 (Type Conversion)

1. 显示转换 (Explicit Conversion)

  • C风格类型转换

    • 改进前: 试图将一个字符串转换为整数,可能导致数据丢失或程序崩溃

      c++ 复制代码
      #include <iostream>
      using namespace std;
      
      int main() {
        const char* str = "123";
        int a = int(str); // 错误!不能直接将字符串指针转换为 int
        cout << "a = " << a << endl;
        return 0;
      }
    • 改进后: 使用 std::stoi 函数将字符串转换为整数

      c++ 复制代码
      #include <iostream>
      #include <string>
      using namespace std;
      
      int main() {
        string str = "123";
        int a = std::stoi(str); 
        cout << "a = " << a << endl;
        return 0;
      }
  • static_cast (C++风格类型转换)

    • 改进前: 试图将一个基类指针转换为派生类指针,如果没有进行动态类型转换可能会导致未定义行为

      c++ 复制代码
      #include <iostream>
      using namespace std;
      
      class Base {};
      class Derived : public Base {};
      
      int main() {
        Base* b = new Base();
        Derived* d = static_cast<Derived*>(b); // 错误!b 实际指向 Base 对象
        delete d; // 未定义行为
        return 0;
      }
    • 改进后: 使用 dynamic_cast 进行安全的向下转型,如果转换不成功会返回 nullptr

      c++ 复制代码
      #include <iostream>
      using namespace std;
      
      class Base {};
      class Derived : public Base {};
      
      int main() {
        Base* b = new Derived();  // 现在 b 指向 Derived 对象
        Derived* d = dynamic_cast<Derived*>(b); // 安全的向下转型
        if (d) { 
          cout << "Successful downcasting." << endl;
          delete d; 
        } else {
          cout << "Failed downcasting." << endl;
        }
        return 0;
      }

2. 隐式转换 (Implicit Conversion)

  • 改进前: 将一个超出范围的值赋给较小的数据类型, 导致数据丢失

    c++ 复制代码
    #include <iostream>
    using namespace std;
    
    int main() {
        int i = 300;
        char c = i; // 警告:数据丢失,因为 char 只能存储 -128 到 127 的值
        cout << "c = " << c << endl; 
        return 0;
    }
  • 改进后: 在赋值之前进行范围检查, 避免数据丢失

    c++ 复制代码
    #include <iostream>
    using namespace std;
    
    int main() {
        int i = 300;
        if (i >= -128 && i <= 127) {
            char c = i; 
            cout << "c = " << c << endl; 
        } else {
            cout << "Value out of range for char type." << endl;
        }
        return 0;
    }

二、自定义类型转换

  • 改进前: 如果没有定义 Animal 到 Dog 的转换构造函数,则无法进行隐式类型转换

    c++ 复制代码
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Animal {
    public:
        Animal(const string& name) : name_(name) {}
        virtual void speak() const { cout << "Animal speaking" << endl; }
        string getName() const { return name_; }
    private:
        string name_;
    };
    
    class Dog : public Animal {
    public:
        Dog(const string& name) : Animal(name) {}
        // 没有定义 Animal 到 Dog 的转换构造函数
        void speak() const override { cout << "Woof!" << endl; }
    };
    
    int main() {
        Animal animal{"Buddy"};
        Dog dog = static_cast<Dog>(animal);  // 错误:无法进行隐式类型转换
        dog.speak();
    
        delete animal;
        return 0;
    }
  • 改进后: 定义从 Animal 到 Dog 的转换构造函数,允许隐式类型转换

    c++ 复制代码
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Animal {
    public:
        Animal(const string& name) : name_(name) {}
        virtual void speak() const { cout << "Animal speaking" << endl; }
        string getName() const { return name_; }
    private:
        string name_;
    };
    
    class Dog : public Animal {
    public:
        Dog(const string& name) : Animal(name) {}
        Dog(const Animal& a) : Animal(a.getName()) {} // 转换构造函数
        void speak() const override { cout << "Woof!" << endl; }
    };
    
    int main() {
        Animal animal{"Buddy"};
        Dog dog = animal; 
        dog.speak(); // 输出 "Woof!"
    
        return 0;
    }
相关推荐
weixin_456904274 小时前
Spring Boot 用户管理系统
java·spring boot·后端
cyforkk5 小时前
Spring 异常处理器:从混乱到有序,优雅处理所有异常
java·后端·spring·mvc
程序员爱钓鱼6 小时前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go
桦说编程6 小时前
爆赞!完全认同!《软件设计的哲学》这本书深得我心
后端
thinktik6 小时前
还在手把手教AI写代码么? 让你的AWS Kiro AI IDE直接读飞书需求文档给你打工吧!
后端·serverless·aws
老青蛙9 小时前
权限系统设计-用户设计
后端
echoyu.9 小时前
消息队列-初识kafka
java·分布式·后端·spring cloud·中间件·架构·kafka
yuluo_YX9 小时前
Go Style 代码风格规范
开发语言·后端·golang
David爱编程9 小时前
从 JVM 到内核:synchronized 与操作系统互斥量的深度联系
java·后端