c/c++整理--c++面向对象(3)
生活随笔
收集整理的這篇文章主要介紹了
c/c++整理--c++面向对象(3)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、與全局對象相比,使用靜態數據成員有什么優勢
優勢: (1)靜態數據成員沒有進入程序的全局命名空間,因此不存在程序中其他全局命名沖突的可能性。 (2)使用靜態數據成員可以隱藏信息。因為靜態數據成員可以是private成員,而全局對象不能二、有哪幾種情況只能用intialization list,而不能用assignment
無論是在構造函數初始化列表中初始化成員,還是在構造函數體中對它們賦值,最終結果都是相同的。不同之處在于,使用構造函數初始化列表初始化數據成員,沒有定義初始化列表的構造函數體中對數據成員賦值。 對于const和reference類型成員變量,它們只能夠被初始化而不能被賦值操作,因此只能使用初始化列表。 還有一種情況就是,類的構造函數需要調用其基類的構造函數的時候。三、靜態成員的錯誤使用
#include <iostream> using namespace std; class test { public: static int i; int j; test(int a):i(1), j(a) {} void func1(); static void func2(); }; void test::func1() { cout<<i<<","<<j<<endl; } void test::func2() { cout<<i<<","<<j<<endl; } int main() { test t(2); t.func1(); t.func2(); return 0; }這個程序有兩個錯誤: (1)代碼第9行不能初始化i (2)代碼第21行,在靜態成員函數中調用了非靜態成員。
改正: #include <iostream> using namespace std; class test { public: static int i; int j; test(int a):j(a) {} void func1(); static void func2(); }; int test::i = 1; void test::func1() { cout<<i<<","<<j<<endl; } void test::func2() { cout<<i<< /*","<<j<<*/ endl; //注釋對j的調用 } int main() { test t(2); t.func1(); t.func2(); return 0; }
總結
以上是生活随笔為你收集整理的c/c++整理--c++面向对象(3)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 伍德里奇计量经济学计算机课后答案第一章,
- 下一篇: 二分法查找(C/C++)