Different Application Methods of C ++ static

Source: Internet
Author: User

There are many differences between the application of C ++ and other languages, especially C. Today, we can analyze the differences in the C ++ static application method. At the same time, we can further master the programming methods of the C ++ language.

Sample Code for C ++ static:

 
 
  1. public class C {   
  2. public static void M() {   
  3. Console.WriteLine("call in class C");   
  4. }   
  5. }  
  6. public class D : C {   
  7. public new static void M() {   
  8. Console.WriteLine("call in class D");   
  9. }   
  10. }  
  11. public class E<T> where T : C {   
  12. public static void N() {   
  13. T.M();   
  14. }   

The code is incorrect. An instance is not allowed to call a static method. If you compile the SDK, the following message is displayed:

 
 
  1. Error 2 'T' is a 'type parameter', 
    which is not valid in the given context 

Why? From the perspective of language design, for the above Code, only one of the following three cases can be true.

  • How to disable the C ++ heap object
  • How to disable C ++ stack objects
  • Basic concepts of C ++ Functions
  • Discussion on the basic content of the variable parameter table in C ++
  • Function Comparison of various C ++ memory regions

1. The statement is incorrect.

2. E. N () CILS C.M () no matter what T is.

3. E. N () callc.m () but E. N () calld.m ().

If the design follows 2, the user expects to execute the method M of class D instead of C when T is class D. Static is static because it can be exactly determined at the time of compilation, or this method can be determined at the Static code analysis stage. Therefore, if we design it in the 3 way, we violate this principle. In this way, there is only 1.

Another explanation:

1. virtual static. Why is there no such thing?

2. No such pointer.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.