本文主要讲述的是值类型和引用类型的赋值及深拷贝
对值类型和引用类型的定义以及由来不清晰的可以看我之前的随笔,链接如下:
https://www.cnblogs.com/ShawBlack/p/16997772.html
由值类型和引用类型定义得知,值类型变量中存储的是其数据本身,而引用类型中存储的是数据的地址。
所以很明显,在我们使用赋值符号时
对于引用类型,直接赋值,很明显只是把地址赋值给新的引用类型变量了,使得二者指向的是同一对象。对于引用类型变量的多次赋值,其实也只是多次赋值地址而已。
举个栗子:
C#:
internal class Program { static void Main(string[] args) { WeatherForecast weatherForecast1 = new WeatherForecast() { TemperatureC = 111, Date = Convert.ToDateTime("1111.01.01") }; WeatherForecast weatherForecast2 = new WeatherForecast() { TemperatureC = 222, Date = Convert.ToDateTime("2222.02.02") }; // WeatherForecast weatherForecast_forCopy = weatherForecast1; //将weatherForecast1中的地址赋值给weatherForecast_forCopy,使得二者指向同一个对象 weatherForecast_forCopy.Date = Convert.ToDateTime("3333.03.03"); weatherForecast_forCopy.TemperatureC = 333; Console.WriteLine("weatherForecast1.TemperatureC = " + weatherForecast1.TemperatureC); Console.WriteLine("weatherForecast1.Date = " + weatherForecast1.Date.ToLongDateString()); // weatherForecast_forCopy = weatherForecast2;//将weatherForecast2中的地址赋值给weatherForecast_forCopy,使得二者指向同一个对象 weatherForecast_forCopy.Date = Convert.ToDateTime("4444.04.04"); weatherForecast_forCopy.TemperatureC = 444; Console.WriteLine("weatherForecast1.TemperatureC = " + weatherForecast1.TemperatureC); Console.WriteLine("weatherForecast1.Date = " + weatherForecast1.Date.ToLongDateString()); Console.WriteLine("weatherForecast2.TemperatureC = " + weatherForecast2.TemperatureC); Console.WriteLine("weatherForecast2.Date = " + weatherForecast2.Date.ToLongDateString()); } } public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } }
结果:
C++:
标签:weatherForecast1,weatherForecast,TemperatureC,forCopy,Date,类型,拷贝,赋值 From: https://www.cnblogs.com/ShawBlack/p/16998770.html