設計乙個類

2021-07-22 08:06:28 字數 1031 閱讀 9902

1、設計乙個不能被繼承的類

1)將建構函式設為私有

此時子類不能訪問基類的建構函式,因此建立子類時就會報錯(無法訪問private成員)

class base_uninherit

base_uninherit(const base_uninherit& rhs){}

base_uninherit& operator=(const base_uninherit& rhs)

public:

static base_uninherit* construct()

~base_uninherit();

};class derived_uninherit:public base_uninherit;

這種情況下,雖然基類不能被繼承,但是基類也不能在棧上初始化,只能通過類靜態方法的形式在堆上建立乙個物件。

2)利用友元類

首先宣告乙個輔助的模板基類,將其建構函式設為私有,只有宣告的友元類可以訪問。則所有以finalclass形式繼承該基類的類都不能再被繼承。並且finalclass可以同時在堆和棧上建立。

templateclass base

~base(){}

};class finalclass:virtual

public base

~finalclass(){}

};

2、如何保證只能在堆上建立物件

將析構函式設為私有

c++是靜態繫結語言,因此在編譯期,所有的非虛函式都必須分析完成。即使是虛函式,也要檢查可訪問性。

當在棧上建立物件時,物件會自動析構,這就要求析構函式必須可以訪問。

而在堆上建立物件時,析構的時機由程式設計師控制,因此不一定需要析構函式

因此當析構函式是私有的,如果在棧上建立物件,編譯就會報錯

3、如何保證只能在棧上建立物件

在堆上建立物件都是通過new操作符來實現的,因此禁用new操作符,將operator new設為私有的就可以保證不能在堆上建立物件

設計乙個Logger類

需求 想要實現乙個logger可以以以下方式使用 logger log 2013 03 05.log log this is a logger test endl log value of temp temp endl log array index array index endl 實現有一點類似...

設計乙個類,用get,set

建立乙個people類,裡面包含 名字 年齡 兩個成員變數,以及這兩個成員的get,set方法 要求用標頭檔案 實現檔案的標準格式實現,然後可以在main函式裡直接建立people物件 第一步 建立控制台程式 include stdafx.h include people.h include inc...

設計乙個user類(Java)

class user 無參,在此用於返回count,並且無引數也不會報錯 public user string name 為使用者名稱賦值,只輸姓名不會報錯 public user string name,string password 為使用者名稱和口令賦值,三種呼叫方式都可以 public st...