对 readonly keyword 和 const keyword 的 见解

本文详细解析了C++中的const与readonly关键字的使用位置、赋值方式,帮助开发者掌握这两者在不同场景下的应用。

1、首先,让我们了解下,它们各自使用的位置!

readonly 只能用于修饰成员变量

const 可用于修饰 成员变量局部变量。

 

2、赋值方式

const 字段是编译时常数,只能在声明的同时,给定一个值,并且该值必须是常量 或者是 可直接计算的表达式

readonly 字段可以是运行时常数。它可以在两个地方初始化, 声明 和 构造函数中。如果,声明和构造函数中,都

给了值,最后的值,是构造函数中给定的值.

 

import relationalStore from '@ohos.data.relationalStore'; import { BookModel } from './BookModel'; import { BusinessError } from '@ohos.base'; // 声明接口类型(解决arkts-no-untyped-obj-literals错误) interface BookValueBucket { title: string; content: string; } export class DatabaseHelper { private static instance: DatabaseHelper; private rdbStore: relationalStore.RdbStore | null = null; private readonly DB_NAME: string = 'book_reader.db'; private readonly DB_VERSION: number = 1; private readonly TABLE_NAME: string = 'books'; private constructor() {} public static getInstance(): DatabaseHelper { if (!DatabaseHelper.instance) { DatabaseHelper.instance = new DatabaseHelper(); } return DatabaseHelper.instance; } // 初始化数据库 public async initDatabase(context: Context): Promise<void> { if (this.rdbStore) { console.warn('Database already initialized'); return; } const config: relationalStore.StoreConfig = { name: this.DB_NAME, securityLevel: relationalStore.SecurityLevel.S1 }; const SQL_CREATE_TABLE = ` CREATE TABLE IF NOT EXISTS ${this.TABLE_NAME} ( id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, content TEXT NOT NULL ) `; try { this.rdbStore = await relationalStore.getRdbStore(context, config); await this.rdbStore.executeSql(SQL_CREATE_TABLE); console.log('Database initialized successfully'); } catch (err) { const error = err as BusinessError; console.error(`Failed to initialize database: code=${error.code}, message=${error.message}`); throw new Error(`Database initialization failed: ${error.message}`); } } private checkDatabaseInitialized(): void { if (!this.rdbStore) { throw new Error('Database not initialized. Call initDatabase() first.'); } } public async addBook(book: BookModel): Promise<number> { // 简化的初始化检查 if (!this.rdbStore) { throw new Error('请先调用initDatabase初始化数据库'); } // 最简化的ValuesBucket使用方式 const valueBucket = { 'title': book.title, 'content': book.content } as relationalStore.ValuesBucket; try { // 直接返回Promise结果 return await this.rdbStore.insert(this.TABLE_NAME, valueBucket); } catch (err) { console.error('添加书籍失败:', JSON.stringify(err)); throw new Error('添加书籍失败'); } } // 4. 明确的类型处理(解决Promise<number>类型问题) const insertId: number = await this.rdbStore.insert(this.TABLE_NAME, valueBucket); return insertId; } catch (err) { // 5. 完善的错误处理 const error = err as BusinessError; console.error(`Failed to add book: code=${error.code}, message=${error.message}`); throw new Error(`Failed to add book: ${error.message}`); } } // 获取所有书籍 public async getAllBooks(): Promise<BookModel[]> { this.checkDatabaseInitialized(); const columns = ['id', 'title', 'content']; const predicates = new relationalStore.RdbPredicates(this.TABLE_NAME); try { const resultSet = await this.rdbStore!.query(predicates, columns); const books: BookModel[] = []; while (resultSet.goToNextRow()) { const book = new BookModel( resultSet.getString(resultSet.getColumnIndex('title')), resultSet.getString(resultSet.getColumnIndex('content')) ); book.id = resultSet.getLong(resultSet.getColumnIndex('id')); books.push(book); } resultSet.close(); return books; } catch (err) { const error = err as BusinessError; console.error(`Failed to get books: code=${error.code}, message=${error.message}`); throw new Error(`Failed to get books: ${error.message}`); } } // 搜索书籍 public async searchBooks(keyword: string): Promise<BookModel[]> { this.checkDatabaseInitialized(); const columns = ['id', 'title', 'content']; const predicates = new relationalStore.RdbPredicates(this.TABLE_NAME); predicates.contains('title', keyword); try { const resultSet = await this.rdbStore!.query(predicates, columns); const books: BookModel[] = []; while (resultSet.goToNextRow()) { const book = new BookModel( resultSet.getString(resultSet.getColumnIndex('title')), resultSet.getString(resultSet.getColumnIndex('content')) ); book.id = resultSet.getLong(resultSet.getColumnIndex('id')); books.push(book); } resultSet.close(); return books; } catch (err) { const error = err as BusinessError; console.error(`Failed to search books: code=${error.code}, message=${error.message}`); throw new Error(`Failed to search books: ${error.message}`); } } // 根据ID获取书籍 public async getBookById(id: number): Promise<BookModel | undefined> { this.checkDatabaseInitialized(); const columns = ['id', 'title', 'content']; const predicates = new relationalStore.RdbPredicates(this.TABLE_NAME); predicates.equalTo('id', id); try { const resultSet = await this.rdbStore!.query(predicates, columns); if (resultSet.goToFirstRow()) { const book = new BookModel( resultSet.getString(resultSet.getColumnIndex('title')), resultSet.getString(resultSet.getColumnIndex('content')) ); book.id = resultSet.getLong(resultSet.getColumnIndex('id')); resultSet.close(); return book; } resultSet.close(); return undefined; } catch (err) { const error = err as BusinessError; console.error(`Failed to get book: code=${error.code}, message=${error.message}`); throw new Error(`Failed to get book: ${error.message}`); } } // 关闭数据库 public async close(): Promise<void> { if (this.rdbStore) { try { await this.rdbStore.close(); this.rdbStore = null; console.log('Database closed successfully'); } catch (err) { const error = err as BusinessError; console.error(`Failed to close database: code=${error.code}, message=${error.message}`); } } } }修正代码,给出简单不易报错的代码
06-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值