您的位置:首页 > 编程语言 > C语言/C++

c# vs c++

2014-06-30 21:45 148 查看
c# vs c++

1、在 C++ 中,类和结构实际上是相同的,而在 C# 中,它们很不一样。C# 类可以实现任意数量的接口,但只能从一个基类继承。而且,C# Struct不支持继承,也不支持显式默认构造函数(必须提供参数化构造函数)。

  1)It is an error to define a default (parameterless) constructor for a struct. It is also an error to initialize an instance field in a struct body. You can initialize struct members only by using a parameterized constructor or by accessing the members individually after the struct is declared. Any private or otherwise inaccessible members can be initialized only in a constructor.

  2) A struct cannot inherit from another struct or class, and it cannot be the base of a class. A struct can implement interfaces, and it does that exactly as classes do.

  3)A struct is a value type, while a class is a reference type

  4)When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. In such a case, there is no constructor call, which makes the allocation more efficient. However, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

  5)下述代码,把struct换成class会导致编译错误

public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";

public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee : Person
{
public string id = "ABC567EFG";
public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}

class TestClass
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
/*
Output
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
*/


View Code
8、C++ 通过继承支持方法的隐式“隐藏”。在 C# 中,必须使用 new 修饰符来显式隐藏继承的成员。

9、预处理器指令用于条件编译。C# 中不使用头文件。

10、static const不能同时使用,因为在一个类,const变量实际上就是一个static变量。

11、在 C# 中,只有在 unsafe 模式下才允许使用指针。

12、在 C++ 中,字符串只是字符的数组。在 C# 中,字符串是支持可靠搜索方法的对象。

13、在 C++ 中,多个模块公用的类型放置在头文件中。在 C# 中,可通过元数据获取此信息。

14、C# 中的局部变量在初始化前不能使用。

15、C# 不支持位域。

参考:

1、http://msdn.microsoft.com/zh-cn/library/8b0bdca4(v=vs.90).aspx

2、http://msdn.microsoft.com/zh-cn/library/6x16t2tx(v=vs.90).aspx

3、http://msdn.microsoft.com/zh-cn/library/yyaad03b(v=vs.90).aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: