C++ static不同的应用方式

开发 后端
C++ static在实际编程中的应用与C语言相比有很多不同之处。我们今天将会针对这两种不同的应用做一个对比,方便大家理解。

C++编程语言的应用方式和其他语言特别是C语言有很多不同之处。那么今天大家就可以从C++ static的应用方法来分析一下它的不同之处到底体现在哪里。同时又能让大家进一步掌握C++语言的编程方法。

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. }   

代码是错误的,不允许一个instance来call一个static method。如果你编译的话,会提示:

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

为什么?从语言设计的角度来看,针对上面的代码,下面的三种情况只能有一种为true。#t#

1. 本身就是错误的写法

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

3. E.N() calls C.M() but E.N() calls D.M().

如果按照2设计,会有用户期望当T是class D的时候,执行class D的method M,而不是C。Static之所以是static,因为它在编译时刻就可以被确切的determined,或者说,在静态代码分析阶段,这个方法就可以被确定了。所以,如果按照3的方式来设计,我们就违背了这个原则。这样,只有1了。

另外的解释:

1. virtual static,为什么没这个东西?

2. 没有this指针而已(以上内容转自同事的一个blog,做了简单的修改)

不过,不清楚C++里面为什么允许这么做?

  1. public class Test{  
  2. public static void Say(){}  
  3. }  
  4. Test t;  
  5. Test* t2 = new Test();  
  6. t.Say();  
  7. t2->Say(); 

以上就是对C++ static的相关应用方法。

责任编辑:曹凯 来源: 博客园
相关推荐

2010-02-04 14:29:45

C++ typenam

2010-02-06 14:12:54

C++继承方式

2010-02-04 16:39:26

C++析构函数

2010-02-04 15:41:10

C++内存管理

2010-02-02 14:27:54

C++ static关

2010-02-06 17:39:52

C++ strtok

2010-02-05 16:46:58

C++ TinyXml

2011-04-07 16:34:05

staticC++

2010-02-06 16:39:45

C++ assert(

2010-02-04 13:39:44

C++数组参数

2010-02-06 16:21:35

C++常规DLL

2010-02-04 16:52:45

C++显式转换

2010-02-03 10:11:17

C++动态数组

2010-02-05 10:30:02

C++操作符重载

2010-01-18 16:42:13

C++类

2010-02-03 16:29:19

C++ sizeof

2010-02-04 11:15:28

C++模板限制

2010-02-03 17:06:36

C++对象复制

2010-02-05 14:12:46

C++声明放置

2010-02-02 14:45:35

C++ typeof
点赞
收藏

51CTO技术栈公众号