求 cpp 熟手移植一个简单的 java 类
面临的主要问题就是成员变量类型的选择:
到底是用 char* 好还是用 std::string 好呢?
其次就是 cpp 里面 getter & setter 的写法,怎么写才不会导致内存泄露?
(最好能给个安全赋值的例子)
以前开发游戏的时候使用过 box2d,里面的getter&setter 实现的方法前面 都加上了 inline 的修饰符,
感觉有点儿疑惑,那个加与不加有何区别?
package com.test.json;
public class Account {
private String name;
private String password;
public Account() {
}
public Account(String name, String password) {
super();
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
问题大概就这么多,先谢谢了! cpp
[解决办法]
当然是 std::string
用 char* 要自己管理指针, 就容易出现内存泄漏. std::string 会帮你管理内存, 就不会出现内存泄漏了.
inline 只是只是提示编译器内联, 提高速度. 和内存泄漏无关.
[解决办法]
到底是用 char* 好还是用 std::string 好呢?
成员变量用std::string 虽然不如CString,但也是个类,而且可移植
所有传入参数使用 const char* 内部修改string对象的值即可,getter建议返回指针或者引用 但是const禁止修改,这样就没有复制动作
C++类定义写在class声明文件里面的函数缺省都是inline,写在外面仍作为内联可能需要加此关键字
[解决办法]
class Account
{
private:
string name;
string password;
public:
Account() { }
Account(string name, string password)
{
this->name = name;
this->password = password;
}
string getName() {
return name;
}
void setName(string name) {
this->name = name;
}
string getPassword() {
return password;
}
void setPassword(string password) {
this->password = password;
}
};
inline就是为了提高程序运行速度,具体的去查查inline。不过inline修饰的函数必须在头文件中定义和实现。
[解决办法]
入参没有必要用const char*,这样参数只能接收const char*
如果用const string&,则const char*和string都能接收
[解决办法]
Account(string name, string password)
{
this->name = name;
this->password = password;
}
====>
Account(string const& name, string const& password)
{
this->name = name;
this->password = password;
}
为什么是 string const& 而不是 const string& ?个人感觉后者的书写方式更为让人理解
二者完全等价。