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;
    }
相关推荐
AntBlack10 小时前
虽迟但到 :盘一盘 SpringAI 现在发展得怎么样了?
后端·spring·openai
ss27311 小时前
手写Spring第4弹: Spring框架进化论:15年技术变迁:从XML配置到响应式编程的演进之路
xml·java·开发语言·后端·spring
舒一笑11 小时前
🚀 PandaCoder 2.0.0 - ES DSL Monitor & SQL Monitor 震撼发布!
后端·ai编程·intellij idea
Java中文社群11 小时前
服务器被攻击!原因竟然是他?真没想到...
java·后端
helloworddm12 小时前
Orleans 流系统握手机制时序图
后端·c#
开心-开心急了13 小时前
Flask入门教程——李辉 第三章 关键知识梳理
后端·python·flask
Code blocks14 小时前
GB28181视频服务wvp部署(一)
java·spring boot·后端
我命由我1234514 小时前
Spring Boot - Spring Boot 静态资源延迟响应(使用拦截器、使用过滤器、使用 ResourceResolver)
java·spring boot·后端·spring·java-ee·intellij-idea·intellij idea
华仔啊15 小时前
3 分钟让你彻底搞懂 Spring 观察者和发布者模式的本质区别
java·后端
言之。15 小时前
LiteLLM:让LLM调用变得简单统一
后端·python·flask