开发者

Is partial class in C# and in C++ defining functions in multilple CPP files are same?

In C++ we can declare a class in a .h file and can have the definitions for functions across multiple files. Is this concept same by using partial keyword with class开发者_JAVA技巧es in C#?


Yes and No.

The main reason for partial is that different parties (you and 1+ tools/designers) can each have their own part of a class to work with. In C++ this would require splitting the actual class definition over multiple .h files, not possible.

But in the end all code is merged by the compiler (linker) into 1 class definition that must be consistent with all the rules.


No it's not. The partial keyword in C# allows you to add new methods and members to a class. In c++, once a class is defined in a header, you need to change that header in order to change the class, you can't just declare new methods/members in a different header.

C#:

class A{
   public void f(){}
}

//other file:
partial class A{
   public void g(){}
}

Now class A has both functions f and g. In C++ however, once you define:

class A{
    public:
       void f();
}

f will become the only method in A. You can't declare new methods in a new header file nor define methods that are not in the class definition in cpp files.


Aparently partial keyword in C# should only be used to separate data automatically generated by Visual Studio (user interface components) from your code. If you're tempted to use it for splitting your big class, then most probably you should consider splitting it to a few smaller classes.


There is one reason why it is not the same that wasn't mentioned in other answers: the CLR, as the JVM, works with classes, so the notion of a class is kept in the compiled code. Standard C++ usually compiles to object formats that have no notion of classes. For this reason the C++ complier has to change function names to ensure that they are unique to the linker that will put together the resulting library or executable. This process is known as "mangling".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜