static和不完全类型的一个例子
生活随笔
收集整理的這篇文章主要介紹了
static和不完全类型的一个例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一個簡單例子
#include <string> #include <iostream> using namespace std; class Test {public:private:int a;int b;//非const的static類型只能在類外定義,這里是聲明static int c;//非const的static類型只能在類外定義,這里是聲明static int ret();//Test類型是不完全類型,只能定義這個類型的引用或者指針,或者聲明(不能定義)不完全類型作為參數或者返回類型的函數,順便提一下,下面t1和t2是定義性聲明,又叫定義又叫聲明Test &t1;//incomplete type 定義性聲明t1Test *t2;//incomplete type 定義性聲明t2Test com(Test t1,Test t2)const; };//非const的static成員在類外,因為static函數沒有this指針,所以只能使用static成員,不能使用普通成員 int Test::c = 1234; //非const的static成員在類外定義,因為static函數沒有this指針,所以只能使用static成員,不能使用普通成員 int Test::ret(){return c;} //成員函數在類外定義 Test Test::com(Test t1,Test t2)const{ if(t1.a > t2.a)return t1; else return t2; }int main() {return 0; }?第二個稍微長點:
文件a.h
#ifndef A_H #define A_H#include <string> #include <iostream> #include "memory" #include "b.h" class Test; using namespace std;void print(Test *); #endif文件b.h?
#ifndef INCLUDE_TEST2 #define INCLUDE_TEST2 #include <string> #include <iostream> #include "a.h"using namespace std; class Test; extern void print(Test *); class TestMgr{ public:friend void print(Test *);void clear(Test ); private: };class Test {public:friend void print(Test *);Test() = default;friend void TestMgr::clear(Test);private:int a;int b;static int c;static int ret();//Test &t1;//incomplete type //Test *t2;//incomplete typeTest com(Test t1,Test t2)const; };#endif文件func.cc?
#include "a.h" #include <iostream> #include <string> #include "b.h" using namespace std; void print(Test *t) { cout << t->a << endl; cout << t->b << endl; cout << "This is a test" << endl; }int Test::c = 1234; int Test::ret(){return c;} Test Test::com(Test t1,Test t2)const{ if(t1.a > t2.a)return t1; else return t2; }void TestMgr::clear(Test t) {}文件main.cc?
#include <string> #include <iostream> #include "a.h" #include "b.h" using namespace std;int main() { Test t; Test *t1 = &t; print(t1);return 0; }main.cc和func.cc兩個文件一起編譯:?
g++ main.cc func.cc -o 123 與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的static和不完全类型的一个例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++中声明和定义的区别(这个兄弟写的解
- 下一篇: c++类名字查找与类的作用域